text:
Function of rxAlign parameter in the PCD_ReadRegister function in MFRC522 Library
I'm trying to port the MFRC522 Arduino library (from GitHub) to the ARM MCUs.
My problem is with the PCD_ReadRegister function:
/**
 * Reads a number of bytes from the specified register in the MFRC522 chip.
 * The interface is described in the datasheet section 8.1.2.
 */
void MFRC522::PCD_ReadRegister( byte reg,       ///< The register to read from. One of the PCD_Register enums.
                                byte count,     ///< The number of bytes to read
                                byte *values,   ///< Byte array to store the values in.
                                byte rxAlign    ///< Only bit positions rxAlign..7 in values[0] are updated.
                                ) {

    if (count == 0) {
        return;
    }
    //Serial.print(F("Reading "));  Serial.print(count); Serial.println(F(" bytes from register."));
    byte address = 0x80 | (reg & 0x7E);     // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
    byte index = 0;                         // Index in values array.
    SPI.beginTransaction(SPISettings(SPI_CLOCK_DIV4, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
    digitalWrite(_chipSelectPin, LOW);      // Select slave
    count--;                                // One read is performed outside of the loop
    SPI.transfer(address);                  // Tell MFRC522 which address we want to read
    while (index < count) {
        if (index == 0 && rxAlign) {        // Only update bit positions rxAlign..7 in values[0]
            // Create bit mask for bit positions rxAlign..7
            byte mask = 0;
            for (byte i = rxAlign; i <= 7; i++) {
                mask |= (1 << i);
            }
            // Read value and tell that we want to read the same address again.
            byte value = SPI.transfer(address);
            // Apply mask to both current value of values[0] and the new data in value.
            values[0] = (values[index] & ~mask) | (value & mask);
        }
        else { // Normal case
            values[index] = SPI.transfer(address);  // Read value and tell that we want to read the same address again.
        }
        index++;
    }
    values[index] = SPI.transfer(0);            // Read the final byte. Send 0 to stop reading.
    digitalWrite(_chipSelectPin, HIGH);         // Release slave again
    SPI.endTransaction(); // Stop using the SPI bus

} // End PCD_ReadRegister()

I read the datasheet several times & can't understand what's the function of this parameter!
Based on datasheet for reading a register from rc522:

Concerning the image in your post about 'SPI Read Data', that simply says the first byte received over MISO is discarded, which is done in PCD_ReadRegister() right before the for loop, and then n bytes are read, with 0 transferred the last time to stop reading.
A quick look at the library and datasheet shows that the rxAlign argument is used in identifying the first valid bit in the first received byte. txLastBits serves a similar purpose, only for transmission of the final byte. Both are written to BitFramingReg of the MFRC522 and are necessary for bit-oriented frames between the MFRC522 and a card/tag.
For example, in the function you have above, if rxAlign = 3, it means only bits 7 to 3 are valid in the first received byte, extracted with bit mask 11111000. So the first valid 'byte' comprises bits 7 to 3 of the first received byte concatenated with bits 2 - 0 of the next received byte. Similarly, in transmission, txLastBits indicates the number of bits of the last byte that are to be transmitted to the card/tag. In both cases, what is transmitted or received over the RF field may not be a multiple of 8, hence the need for these arguments and BitFramingReg.
Anyways, this shouldn't interfere at all with porting the library. Simply replace the Arduino-specific functions/interfaces and allow the library's existing logic to remain as is.

EDIT
I'll try to answer your questions:

In this context, 106kBd refers to the data rate between the RC522 and a card, and not between the RC522 and the MCU. The maximum is about 848kBd, i think. Check the datasheet for more details.
Bit-oriented frames are necessary for the anti-collision process. Superimposed bits in the Manchester encoding, when several cards attempt to communicate with the RC522 at once, require that individual bits be processed as opposed to the usual byte-sized units. Look up anti-collision techniques.
Anticollision is necessary if the same reader will possibly have multiple tags within its range. From an IEEE article:

Tag collisions can impose a major inefficiency in RFID systems, resulting in low identification rates, short reading range and ineffective resource utilization. They are more problematic in passive tags due to limitations on power and functionality.

So, if you will be presenting only one card at a time, then you should be safe without implementing anticollision in your code. Else, I'm afraid you have no choice unless you want to confuse the reader.
If all you want to do is read UIDs and read from/write to blocks on a card (one at a time), you may want to try porting this straightforward MFRC522 UART library, which doesnt implement anitcollision, by the way.
If you still want to port the SPI-based library, then, a few suggestions:
You want to replace the SPI interface with UART. This is low-level stuff, all contained within a few functions like PCD_ReadRegister(), PCD_WriteRegister() and a few others. These functions serve higher-level functions, which have no clue of their internal implementation, but expect certain behaviour from them. Swap the SPI functions for their UART equivalents, as soon as you understand how to talk to the reader over UART. Once your ARM UART functions behave exactly like the SPI functions, your work is almost done; there is no need to learn the reason for everything in the higher-level functions since they dont relate to anything interface-specific. This includes everything concerning rxAlign and whatnot. Good luck :).

Dear Tiste,Really thanks for your great description.Problem is that i must changed libraries used connection peripheral from SPI to UART.3 new question:1-Based on Datasheet page 46-table 48:These bits are only to be used for bitwise anticollision at
106 kBd, for all other modes they are set to 0.then for default 9600 baud rate in uart can i avoid this?2-second question is i understand what is do,but i don't know why we do this yet?why bytes are not formed as usual and are not valid from first bit?why there are avoidable bits in the beginning of data stream?3-is this necessary in UART mode too?

@MahmoudHD I've edited my answer.

@MahmoudHD Does this help? Have you gotten past this?

Dear Tiste,Really appreciated you for your great guidance,I'm trying hard to port an official SPI arduino library of this chip to my target MCU,I will be place to new question here,WBR.

@MahmoudHD You arent porting to UART anymore?

Actually I mean,I'm trying to port SPI version(https://github.com/miguelbalboa/rfid) to initialing with UART yet.Now here we are in new year holidays & after that i will continue to porting that for LPC ARM MCUs,WBR.


text:
COM port problem when uploading bootloader to SAMD21G
I use an ATSAMD21E16B-AU in my circuit and I want to upload the bootloader with the SAM-BA flash programming tool in this official link:
http://www.atmel.com/Images/Atmel-42366-SAM-BA-Bootloader-for-SAM-D21_ApplicationNote_AT07175.pdf.
I will use that directly with USB cable signals D+, D-, 5V, GND (SAMD microprocessor has internal USB serial hardware and D+ D- pins)
Before I try to upload it, it needs to appear in Device Manager on Windows as a "COM port" with EDBG driver. Because it didn't, SAM-BA doesn't show any COM port as EDBG in the "Select the connection" section.
Can I burn a bootloader to ATSAMD without an JTAG device? For example, I want learn if I can do that with Arduino Zero?

External condition: Reset the part and make sure the Hardware Bootloader Entry pin (PA15) is pulled low
when reset is released.  e.g. push button then apply power.

source: Stack Exchange

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

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

sort: votes


text:
DS1307 RTC not working with CC3000 WiFi shield (I2C bus hangs)
I am trying to use a DS1307 (from Sparkfun, BOB-12708) with an Arduino Leonardo. I have connected the SDA, SCL, GND, and 5V pins from the RTC to the Arduino. However, with a CC3000 WiFi shield on the Arduino, the I2C bus hangs. Specifically, Wire.endtransmission() hangs, called by rtc.isrunning(). I have confirmed that it works properly on the same Arduino without the WiFi shield. I am using the ds1307 RTClib example for testing it.

Which CC3000 breakout exactly? This may be related to the fact that the CC3000 employs interrupts; they could be interrupting the I2C transaction. Post the code that combines the CC3000 and the RTC.

It's the CC3000 shield.

Adafruit and Sparkfun both produce CC3000 shields, among others. Which one is yours?

I have the one from Adafruit: https://www.adafruit.com/product/1491

It could be that the CC3000 interrupts are affecting the Wire library's behaviour since the latter is interrupt-driven itself.
Try disabling the CC3000 IRQ before calling rtc.isrunning() or any other RTC functions. First #include "ccspi.h" in your sketch. Then place WlanInterruptDisable() before any RTClib function call, and then WlanInterruptEnable() after the RTC function returns.
Even if this works, it may affect the functionality of the CC3000, since it increases the chances of missed interrupts. You can search for DS1307 libraries that employ SoftwareI2C instead such as this one. They should be better able to recover from the CC3000 interrupts.

As I've said in my OP, it doesn't work even with just the RTC example. Would CC3000 interrupts be messing with things even if the library isn't included?

No, it wouldnt. Somehow, I thought you meant that you used the examples together with the CC3000 code. How are you powering the CC3000? Directly from the Arduino?

The CC3000 is a shield, so yes it is directly powered from the Arduino which is powered by USB for testing.

Powering the CC3000 via USB can cause unreliable behaviour since USB can only supply so much current. Try connecting the shield to the Arduino with jumper cables and powering the shield separately with a 1A source, while connecting all the GNDs together.

I'm pretty sure a USB to wall adapter can supply a lot more current, correct? Might that work? I could probably also rig something up if it doesn't.

Yeah, a USB-wall adapter should be alright, but read the specs on the body, to be sure.

That seems to be part of the solution, but something is still not working and I can't debug it since it has to be connected to the wall. I've been using the builtin LED to debug it, but there's only so much I can do. I tried netcat + a simple CC3000 socket, but it hung on establishing the CC3000 socket on my computer power (expected) and I can't debug it well without Serial. I might look into using two arduinos to assist with debugging later (one with a CC3000 connected to the wall, the other connected to my computer, both connected to each other via digital pins).

It doesnt have to be connected to the wall. You could use 4 1.5V batteries in series to power the CC3000.

For some reason I thought you couldn't have both VIN and USB connected, looking at the documentation it would appear I am wrong. That will be useful. Thank you!

@PlasmaPower Sure. But I wasnt talking about powering the Arduino, only the CC3000. I used batteries for a while, through lots of tests, before they got drained.

I'm using the CC3000 shield, not the breakout however. Powering them separately would be either impossible or at the least very tricky.

Not necessarily. The actual connections from shield to Uno are only 7. Look here: https://learn.adafruit.com/adafruit-cc3000-wifi/connections. You can use male-female jumpers, if you have them. Also how are you connecting the RTC to the Arduino, with the shield on top?

I'm stuck with a Leonardo for now, which also requires the ICSP pins, so I'm not sure if that makes a difference. As for connecting the RTC, the RTC is a breakout of course, and it's connected through SCL and SDA (but currently I'm using SoftI2C).

Let us continue this discussion in chat.

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


text:
Uploading sketch problem
I just plugged my arduino and click upload, it shows this error:
Arduino: 1.8.5 (Windows 7), Board: "Arduino/Genuino Uno"

Sketch uses 948 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Are you sure you board is appearing as COM1?

it was showing COM4

either you are already using the serial port or you just didn't select the port from the arduino "Tools>port"
you can always check your device's communication port using the device manager.

thanks for your precious time,,, the problem was selecting a right port. thanks alot

In the Arduino IDE check for the available ports. Be sure that the COM Port on Windows or ACMO port on Linux based OS is selected.
If the problem continues then check if the port is allowed in Windows and Linux.


text:
Can't display the two float values correctly from pyserial on Arduino's LCD
I transported two float values with pyserial to COM3 and Arduino accepted the values.
But it displayed the first value correctly on LCD, the second value can't be read and showed "nan" on LCD.
Python code:
import serial
import struct
ser =serial.Serial("COM3", 115200, timeout=2)

##======Get  Ready================
print("Connecting to Arduino.....")
for i in range (1,10):
    rv=ser.readline()
    print("Loading...")
    #Debug print (rv) # Read the newest output from the Arduino
    print (rv.decode("utf-8"))
    ser.flushInput()
    sleep(1) # Delay for one tenth of a secon
    Str=rv.decode("utf-8")
    #Debug print(Str[0:5])
    if Str[0:5]=="Ready":
          print("Get Arduino Ready !")
          break
##------------------------------------------------------
d = 77.25
a = 111.32
ser.write(struct.pack('>2f',d,a))

Arduino code:
#include <LiquidCrystal.h>
float x;
byte *xdata = (byte *) & x;
float y;
byte *ydata = (byte *) & y;
int num = 0;
char coor[2];

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  Serial.begin(115200); // set the baud rate
  Serial.println("Ready"); // print "Ready" once
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
}

void loop(){
  while(Serial.available() > 0){
    for(int i = 0; i < 2; i++){
      coor[i] = Serial.read();
      }
    if(coor[0] == 'B' ){
      xdata[3] = coor[0];
      ydata[3] = coor[1];
      num = 1;
    } else if(num == 1){
      xdata[2] = coor[0];
      ydata[2] = coor[1];
      num++;
    } else if(num == 2){
      xdata[1] = coor[0];
      ydata[1] = coor[1];
      num++;
    } else if(num == 3){
      xdata[0] = coor[0];
      ydata[0] = coor[1];
      num = 0;
    // use the values
    Serial.write(xdata,4);
    Serial.write(ydata,4);
    lcd.print(x);
    lcd.setCursor(8,0);
    lcd.print(y);
      }
    }

The LCD monitor will show 77.25 and nan. It can't show 111.32 correctly.

you read two bytes if at least one is available. read the two bytes with Serial.readBytes(coor, 2). it will wait for the second byte

Or wait for there to be 2 bytes available before reading them...

sorry,i still can't unserstand the following code," Serial.readBytes(coor, 2) ",where to write.

I replaced "coor[i] = Serial.read();" with "Serial.readBytes(coor, 2)",but it still can't work.

and you removed the for loop? https://www.arduino.cc/reference/en/language/functions/communication/serial/readbytes/

No,I deleted the  "for(int i = 0; i < 2; i++){ coor[i] = Serial.read(); }" and write "Serial.readBytes(coor, 2);" in while funtion.

the LCD showed different,the 77.25 became 64.25 on LCD monitor,and the nan became -0.00

I don't understand why you read the bytes this way. Your original version was reading only the bytes of the first float into xdata and -1 into ydata. (read returns -1 if no data is available, it doesn't wait.) Now when two bytes are read with readBytes, first two bytes of the first float are written one into xdata[0] and second into ydata[0].
read first float with readBytes(xdata, 4) and the the second with readBytes(ydata, 4)

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


text:
Please help explain the meaning of '\n' and '0';
Please help explain the meaning of '\n' and '0' in the lines
if (isdigit(readValue) && readValue != '\n')
{
  cellValue = cellValue * 10 + readValue - '0';
}

The '\n' in interpreted as a line-feed character.  It is one of many printable and non printable ASCII characters computers use.  Usually, character strings are terminated using a line-feed.  So this line of code is likely testing for the end of a string of characters.
The '0' is interpreted as the ASCII value for the character which looks like the number zero.  Strange enough, when printing characters, the ASCII value for the charter which looks like the number zero actually has a value of 48.  And one has a value of 49.  Two a value of 50.  Three a value of 51. And so on.  So, to convert a number found in a character string into numbers like 0, 1, 2 & 3, programmers subtract 48 from the character.  Using '0' instead of 48 works as both represent the same value.  And, by subtracting '0', it is clearer to the seasoned programmer that a conversion from ASCII numbers to normal numbers is underway.

\n stands for new line feed. It is one of the many "escape sequences" in C. Escape sequences start with "\" and it imply a predefined meaning to compiler.
Refer: https://en.m.wikipedia.org/wiki/Escape_sequences_in_C
In ASCII, decimal numbers from 0-9 are represented in 7-bits, in the range 48-57. So if a and b are integers, then:
b = a - '0' means  b = a - 48
Refer:
https://ascii.cl/index.htm?content=mobile


text:
Grove A12-200 current sensor
I am trying to measure current from an LFG with Arduino Uno and Grove current sensor (A12-200). I found a code at this link you can see Arduino code here.
The code works, but there are some operations that I don't understand. Let me copy and paste the code here (for further information, please follow the link above).
/****************************************************************************/
//  Function: Measure the amplitude current of the alternating current and
//            the effective current of the sinusoidal alternating current.
//  Hardware: Grove - Electricity Sensor
//  Date:    Jan 19,2013
//  by www.seeedstudio.com
#define ELECTRICITY_SENSOR A0 // Analog input pin that sensor is attached to

float amplitude_current;               //amplitude current
float effective_value;       //effective current

void setup()
{
    Serial.begin(9600);
    pins_init();
}
void loop()
{
    int sensor_max;
    sensor_max = getMaxValue();
    Serial.print("sensor_max = ");
    Serial.println(sensor_max);
    //the VCC on the Grove interface of the sensor is 5v
    amplitude_current=(float)sensor_max/1024*5/800*2000000;
    effective_value=amplitude_current/1.414;//minimum_current=1/1024*5/800*2000000/1.414=8.6(mA)
                        //Only for sinusoidal alternating current
    Serial.println("The amplitude of the current is(in mA)");
    Serial.println(amplitude_current,1);//Only one number after the decimal point
    Serial.println("The effective value of the current is(in mA)");
    Serial.println(effective_value,1);
}
void pins_init()
{
    pinMode(ELECTRICITY_SENSOR, INPUT);
}
/*Function: Sample for 1000ms and get the maximum value from the SIG pin*/
int getMaxValue()
{
    int sensorValue;             //value read from the sensor
    int sensorMax = 0;
    uint32_t start_time = millis();
    while((millis()-start_time) < 1000)//sample for 1000ms
    {
        sensorValue = analogRead(ELECTRICITY_SENSOR);
        if (sensorValue > sensorMax)
        {
            /*record the maximum sensor value*/
            sensorMax = sensorValue;
        }
    }
    return sensorMax;
}

effective_value=amplitude_current/1.414

I don't understand why dividing amplitude_current by 1.414 we'll get effective_current.
And in the function getMaxValue(), I know what it does, but I don't understand why we just need maxvalue.

it is a degraded without understanding modified copy-pasted example. btw: the sensor measures to 10 A at 230 V

I don't understan what you mean?

You are measuring a sinusoidal "signal" that is alternating in polarity. What the code notes as "effective" current the equivalent DC current for purposes of measuring power consumption. In EE, it's called "RMS" or Root Mean Square, and it's the mathematical derivation to calculate consumed power or current in a situation where the current flows symmetrically back and forth, and thus a time average would give zero.
It's dividing the peak current by the square-root of 2 (1.414).


text:
Overflow in bit calculation
I'm having a double buffer to write data from sensors to SD card. inBuf points to the buffer that are written into (from sensors). The other buffer write data to SD card.
char buffer[2][BUFLEN];
volatile int inBuf = 0;

inBuf = 1 - inBuf;

However, the update of inBuf does not work. Firstly inBuf is 0, and after that inBuf becomes 32!!! I tried different data types: boolean, uint8_t, int and the results are the same.
How could I fix this problem? Also, what datatype should I use for inBuf, as it's really just one bit?
I ended up using the following:
inBuf = inBuf? 0:1;

but seems really complicated and unnecessary.
EDITS:
Sorry for was not being clear previously. It turns out that I had an overflow in the code:
char buffer[2][BUFLEN];
volatile uint16_t bufferCounter;
volatile int inBuf = 0;
volatile bool outBufHasData = false;

Inside the interrupt handler:
if (bufferCounter < BUFLEN - SAMPLESIZEINCHAR + 1) {
  epoch = now();
  proximity = vcnl.readProximity();
  ambientLight = vcnl.readAmbient();

  // format to be fixed length as opposed to variable length
  // sacrifice overhead in written data with simpler and more robust code
  // since we know exactly how much to increment after each write
  int written = snprintf(&buffer[inBuf][bufferCounter], SAMPLESIZEINCHAR,
        "%10lu,%5d,%5d\n",
        epoch, proximity, ambientLight);

  if (written > 0) {
    bufferCounter += written;
  }
} else {
  // only switch buffer if out buffer is written to SD card
  if (!outBufHasData) {
    inBuf = inBuf? 0:1;
    bufferCounter = 0;
    outBufHasData = true;
  }
}

Then in the for loop, where the buffer is written to SD card when the buffer is full:
  if (outBufHasData) {
    myFile.print(buffer[1 - inBuf]);
    myFile.close();
    outBufHasData = false;
  }

Previously, I had bufferCounter < BUFLEN !! Thus I was writing over the memory of the buffer, and spill into bufferCounter and inBuf. That's why I got the value 32 of inBuf, which is the ASCII code of space. Mystery resolved!!

I see you have inbuf volatile. Is there an interrupt involved somewhere? Care to share your actual code instead of just 2 lines?

You obviously have a bug somewhere, but since it is not in the snippet you posted, we cannot help you. Could you post a Minimal, Complete, and Verifiable example showing the problem?

My guess is that, since inBuf immediately follows buffer in the definitions you are overflowing buffer and clobbering the contents of inBuf - but that's just a guess since we cannot see your code!

@Majenko That's a correct guess! My code has overflow and rewrote the number 1 to by space char, which is 32. If you want you could add an answer and I'll accept that!!

At least part of your edit, whilst clarifying what you are asking, also appears to contain an answer. It would be better to edit your question to clarify the original problem, and then post the solution and explanation as an answer, and then accept your own answer. I will vote to reopen the question, so that you can post your own answer. Your question (and answer) may prove to be useful for someone else.

Seeing  as your data typpe has the volatile keyword maybe the value of inBuf is being changed on another section of code like an interupt, other wise i see no reason for the variable to have a value of 32.
If you want to only use one bit you should just use the boolean data type with a true or false value.
In that bit of code i assume you are trying to invert the value of the bit, with the boolean you could always use the NOT operator:
inBuf != inBuf;

If you want a variable to be 'yes' and 'no' or perhaps '0' and '1', then you can use a boolean which is 'true' or 'false'. With a boolean you can use logic operators:
boolean dataReady = false;
dataReady = !dataReady;
if( dataReady) ...

A boolean on a 8-bit AVR chip (Arduino Uno,Leonardo,Nano,Mega) is 8 bit. You could also use a byte and make it 0 or 1.
A 8-bit variable is often used when a interrupt routine sets a flag. By making that flag only 8 bit and volatile, it can be used in the loop function as well without the need to disable the interrupts. Reading and writing a 8 bit variable can not be interrupted by an interrupt routine.
Using 8 bits when only 1 bit is needed is normal. You don't have to worry about that.
When you need hundreds of 1 bit variables, then it is possible to select each bit with macro's or a lot #define to select each bit. This is almost never used in normal code, but almost always used for the registers of a sensor.
And last but not least: a struct with bit fields packs the bits. That can be handy sometimes.

this answer does not answer the OPs question.

I was trying to see through the little information and tried answer the question that the OP probably should have been asking.

Thank you though, I'll be clear next time asking question!


text:
How to Time the Arduino using RTC that I can operate the valves at 7am, 12pm, and 4 am?
The idea of this project is to open 3 valves one after the other for 5 minutes each, at a time like like 7am, 12pm, 4pm in a day.
The for loop should be executed at 7am, where valve 1 is open and water is pumped for 5 minutes, then valve 1 closes and valve 2 runs for 5 minutes, then valve 3 opens and runs for 5 minutes.
The program comes to a stop. Now at 12pm, the same cycle, or process repeats for the 3 valves.
The question is how do I Time the Arduino using the RTC that I can operate the valves at 7am, 12pm, and 4am?
#include <SoftwareSerial.h>

#include <DS3231.h>

// intialise Valves for Each Vegetation Bed

int valvePorts[] = { 4,5,6};

int valveCount= 3;

DS3231  rtc(SDA, SCL);

Time t;
const int OnHourOne = 12;   // assuming that one Tank- valve takes 5minutes each

const int OnMinOne = 00;

const int OffHourOne = 12;

const int OffMinOne = 30;

const int OnHourTwo = 16;

const int OnMinTwo = 00;

const int OffHourTwo = 16;

const int OffMinTwo = 30;

void setup()

{

 for( int thisvalve=0; thisvalve<=valveCount; thisvalve++)

{

 pinMode(valvePorts[thisvalve], OUTPUT);

}

pinMode(Waterpump,OUTPUT);             // Waterpump

  Serial.begin(9600);
}

void loop()

{

   t = rtc.getTime();

  Serial.print(t.hour);

  Serial.print(" hour(s), ");

  Serial.print(t.min);

  Serial.print(" minute(s)");

  Serial.println(" ");

  delay (1000);

   if(t.hour == OnHour && t.min == OnMin)

{

     Startwatering(1);

    }

    else if(t.hour == OffHour && t.min == OffMin)
{
      Startwatering(0);

    }

void Startwatering(int id)

 {

         if( id== 0)
                  {

                    return;

                  }

     //while(valvePorts[thisvalve],HIGH)

      if(id==1)

     {

   for( int thisvalve=0; thisvalve <=valveCount; thisvalve++)

pinMode(valvePorts[thisvalve], OUTPUT);

   {

  digitalWrite(Waterpump,LOW);

 delay(5000)

  } // close for loop

     }// close if loop

 } // close for loop

Use the Time (previous called TimeLib) library (maintained by Paul Stoffregen) https://www.pjrc.com/teensy/td_libs_Time.html with the TimeAlarms https://www.pjrc.com/teensy/td_libs_TimeAlarms.html

Duplicate of the closed question RTC + Arduino to operate 3 valves in 24 hours

Many ways of doing it.

Poll the rtc constantly until the set time is reached. Then operate the valves. Or
Set an alarm on the rtc for the next time to operate the valves. The rtc will interrupt the mcu when the time is up. The mcu can then operate the valves.

You don't have to use an rtc for this.

So i just use Delay function?


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

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

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

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

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

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

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


text:
The code fails to generate the values I want, when both trigger pins 2, 3 are high or low. Why?
/*aim of the program is to generate 2 different varying frequency from the
same output which is controlled by 2 triggers*/
void setup()
{
    pinMode(2,INPUT); //setting the trigger pins 2,3
    pinMode(3,INPUT);
    pinMode(6,OUTPUT); //output pin
}

void loop()
{
    if(digitalRead(2)==HIGH && digitalRead(3)==LOW) { //trigger conditions
        infra();
    }
    else if(digitalRead(2)==LOW && digitalRead(3)==HIGH) {
        red();
    }
    else if((digitalRead(2)==HIGH && digitalRead(3)==HIGH) || (digitalRead(2)==LOW && digitalRead(3)==LOW)) {
        Serial.println('help');
    }
}

void infra() //function varies sinosoidaly (working)
{
    float f;

    for(f=16000; f<=20525; f+=4.525) {
        tone(6,f);
    }

    for(f=20525; f>=16000; f=f-4.525) {
        tone(6,f);
    }
}

void red() //function varies sinosoidaly (working)
{
    float p;

    for(p=25000; p<=32071; p+=7.071) {
        tone(6,p);
    }

    for(p=32071; p>=25000; p=p-7.071) {
        tone(6,p);
    }
}

'help' is not a string.

the code fails to generate the values i want ... how does it fail?

@gre_gor I think you have found the problem. Would you care to turn your comment into an answer?

@per1234 OP's code doesn't print anything to serial because he is missing serial initialization. Printing 'help' just prints some number.

To send anything to serial you need to initialize it first with:
void setup()
{
    Serial.begin(115200);
    //other code
}

And you are using wrong quotes for the string.
They should be double quotes " not single ones '.
Also you could simplify your code, if you removed the third if, since it's just checking the already known state at that point.
You should also read the button state only once, save them into a variable and then just compare those variables.
bool button1_state = digitalRead(2);
bool button2_state = digitalRead(3);
if (button1_state && !button2_state) {
    infra();
}
else if (!button1_state && button2_state) {
    red();
}
else {
    Serial.println("help");
}


text:
Sodaq Moja — Accessing SW2/SW3 user switches
I have a Sodaq Moja, from supporting the project on Kickstarter, and I didn't have much time until now to play with it. Unfortunately, the online documentation for the Moja has disappeared, and only the docs for the new version, the Mbili, is accessible. And nowhere can I see where to access the user switches. Which, to boot, have been reordered in the Mbili, can cut down from 3 to 2.
Would anyone have an idea?
Cheers,

It took me about 15 seconds to get all the information you could ever want about the Moja, including the schematic.  You didn't try very hard.  Here's the schematic: https://github.com/SodaqMoja/SodaqMojaBoard and there is tons more stuff in other repositories: https://github.com/SodaqMoja

I went through the github repository but didn't find any code related to sw2/sw3. Did you? The 15 seconds you spent were obviously lazy and useless...

I have to ask: what "user switches" are you thinking you are trying to use?  The Moja has no user switches as you can tell by looking at your board and cross-referencing what you see there with what is on the schematic I pointed to.

According to the schematics and pictures of the Moja, the Sodaq Moja has no "User Switches".
There are 2 buttons and 1 switch.  The switch is a general power on-off switch.  One button (SW2) is the master reset button for the ATMega328P.  The other button, SW3, is the reset for the X-Bee daughter board.
None of those can be used programmatically.


text:
How to chose softserial library use on Arduino project?
I want to do a project that has multiple Arduino communication through UART, that project project one of limit is using Arduino Nano (small and cheap). I need to set 4 serial port instance on Nano to connect other nano to receive and write, I searched about serial port of nano that only have one hardware serial port, so after I found the many softserial library such as pre-bulite softserial and altsoftserial NeoSWSerial and NeoHWSerial and NeoICSerial.
Because library too libraries i don't know which one can help complete my project.

what's wrong with the arduino softwareserial library? in what way does it not work for you?

Is using UART a hard requirement?
If not, consider using an I2C connection which uses a single connection and addresses to communicate with many devices.

I think your problem is that you need 4 serial ports.
With software serial that's just not going to happen:

SoftwareSerial can only receive on one serial port at any given time.
AltSoftSerial is limited to specific pins, and only one instance because there is only one set of pins
NeoSWSerial is kind of between the two. More efficient than SoftwareSerial, but still (as far as I can tell) limited to one instance (it uses a timer interrupt to drive the communication, so can use any pins)

If you need communication between lots of devices over serial then you will either need devices with more hardware serial ports (Arduino Mega, for example), or implement a multi-drop bus system (like RS-485) which only needs one serial port to communicate with many devices. Extra external hardware is required though.

Good answer. Another hardware option is a SPI to UART expander.


text:
How to fix this error?
Arduino: 1.8.8 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"
libraries\TimerOne\TimerOne.cpp.o (symbol from plugin): In function `TimerOne::isrDefaultUnused()':

(.text+0x0): multiple definition of `__vector_13'

libraries\Timer1Fast\Timer1Fast.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

Multiple libraries were found for "Timer1Fast.h"
 Used: D:\apps\Arduino\libraries\Timer1Fast
 Not used: C:\Users\biril\Documents\Arduino\libraries\pwmTest
Multiple libraries were found for "TimerOne.h"
 Used: D:\apps\Arduino\libraries\TimerOne
 Not used: C:\Users\biril\Documents\Arduino\libraries\TimerOne-master
Multiple libraries were found for "LiquidCrystal_I2C.h"
 Used: C:\Users\biril\Documents\Arduino\libraries\LiquidCrystal_I2C
 Not used: C:\Users\biril\Documents\Arduino\libraries\NewliquidCrystal
 Not used: C:\Users\biril\Documents\Arduino\libraries\Arduino-LiquidCrystal-I2C-library-master
 Not used: D:\apps\Arduino\libraries\LiquidCrystal
Multiple libraries were found for "Wire.h"
 Used: D:\apps\Arduino\hardware\arduino\avr\libraries\Wire
 Not used: D:\apps\Arduino\libraries\Wire
exit status 1
Error compiling for board Arduino Nano.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

What code causes this error? I think you have two libraries that both use the hardware "timer1".

Don't use both the TimerOne and Timer1Fast libraries together. Why you would want to, though, is anyone's guess...

thanks, i'll rearrange my libraries again.


text:
Gps with Lora (E32 433T30D)
I want to receive data from GPS Neo 6m to Arduino and want to sent through LoRa (E32 433T30D).
GPS RECEIVE AND LORA SEND code
#include <SoftwareSerial.h>
#include <TinyGPS++.h>

static const int RXPin = 4, TXPin = 5;
static const int loraRXPin = 2, loraTXPin = 3;
static const uint32_t GPSBaud = 9600;
static const uint32_t loraBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);
SoftwareSerial lora(loraRXPin, loraTXPin);

void setup(){
  Serial.begin(9600);
  ss.begin(GPSBaud);
  ss.println("KATHE");
  lora.begin(loraBaud);
  lora.println("ASHOK");
}

void loop() {
  // This sketch displays information every time a new sentence is correctly encoded.
  while (ss.available() > 0){
    gps.encode(ss.read());
    if (gps.location.isUpdated()){
      ss.listen();
      Serial.print("Latitude= ");
      Serial.print(gps.location.lat(), 6);
      Serial.print(" Longitude= ");
      Serial.println(gps.location.lng(), 6);
      lora.listen();
      lora.print("Latitude= ");
      lora.print(gps.location.lat(), 6);
      lora.print(" Longitude= ");
      lora.println(gps.location.lng(), 6);
    }
  }

  }

LORA RECEIVE CODE is

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2,3); // RX, TX

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

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
    //Serial.println(" ");
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());

  }
}

Here I'm not getting gps data to the LoRa receiver.
Please help me to overcome this problem.

set ss.listen() in setup(). you don't read lora so why listen? are the gps data printed to Serial Monitor?

Thank you for your reply.  No I'm not getting gps data to the serial monitor or through lora. But individual codes if I run, getting data. Only whenever ever I'm clubbing the both codes I'm not getting the data

did you made the change I recommended? (the individual codes don't have two SoftwareSerial instances)

Yes I got it. At sending code no need create another serial port, we can directly use LoRa Rx and Tx to the arduino uno 0 and 1. If I use this method I'm getting data to the Receiver. Thank you so much for your reply.

Lora we can connect directly to the arduino serial ports(0,1)- Lora Tx is connected to the arduino Rx and Lora Rx is connected to the arduino Tx. (this is for receiving data from arduino and must be connected these pins after uploading the code).
(2,3) of other arduino to receive data to arduino from Lora.
For sending there is no code like Bluetooth. And for receiving the following code helps you..
include  SoftwareSerial mySerial(2,3); // RX, TX void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native j for the SoftwareSerial port mySerial.begin(9600); mySerial.println("Hello, world?"); } void loop() { // run over and over if (mySerial.available()) { Serial.write(mySerial.read()); //Serial.println(" "); } if (Serial.available()) { mySerial.write(Serial.read()); } }


text:
Missing time when using timer
I have set up Timer2 to count every tick at 16MHz, or 62.5ns per tick. Then I run the following code:
int t = 0;
    for (int i=0;i<64;i++){
  data[4*i] = TCNT2;
  data[4*i+1] = TCNT2;
  byte now = data[4*i+1];
  byte last = data[4*i];
  t += now > last? (long)(now-last) : 256 -(long)(last-now);
  data[4*i+2] = TCNT2;
  data[4*i+3] = TCNT2;
  }
}
for (int i=0;i<255;i++){
  Serial.println(data[i]-data[i+1]);
}

and I get the output: "4 4 4 11" (repeated) which makes sense, 4 clock cycles to read TCNT2 and write it to the correct place in data and 11 cycles when also evaluating the loop condition. However, I can't understand when the variable t is updated. I have tried running with and without t and both give the same timings. From my (obviously lacking) understanding updating a variable is at minimum one instruction, so how can it do it under one clock cycle? Am I misunderstanding what one instruction is or does the TCNT2 counter for the timer not update accurately here?

Ops, I just realized it's the compiler working it's magic. I never used t, thus the compiler said "Wtf is this guy doing, this t is useless and I'll remove it!". When I used t I got sensible results.


text:
What is the maximum "wattage" can be pushed into an ATMega328 ADC pins?
I was doing some Ohm's Law calculations to calculate the voltage output from a 2-resistor voltage divider, the input will be with a maximum of 12 volts, I want the ATMega328 to measure that voltage, so I simply thought of putting two resistors in series with values of 330 ohms and 220 ohms like this:

simulate this circuit – Schematic created using CircuitLab
Theoretically on paper the maximum voltage outputting from the node going to the ATMega328 is ~4.8V, but I want a special safety feature, I want to put in mind that at anytime the ground connection can be hung open (to simulate a lose breadboard connection, bad soldering joint etc...) now based upon my understanding if there is no ground connection, the voltage going to the Arduino will be 12V which is a killer, as after looking on the ATMMega328 datasheet it states that

28.1 Absolute Maximum Ratings. Voltage on any pin except RESET with respect
to ground => VCC + 0.5

The current will be limited by the 330ohm resistor to only 36mA which I think is a lot, I thought of doubling the resistors values to 330000 and 220000 by that the current will be limited to only 36uA. Again based upon my understanding there is still 12V going to the Arduino but wouldn't it directly drop if the ground connection was cut off ? That's why I ask what is the maximum input power to an Arduino?

This is actually a special case that is undocumented, and in fact not as simple as you would at first think.
The input port itself is not actually what is in question here. Instead every IO pin on the Arduino, be it set to INPUT or OUTPUT, has a set of ESD protection diodes on them. These look like this:

simulate this circuit – Schematic created using CircuitLab
The "IO MODULE" when in INPUT mode can pretty much be ignored, since it is a very high impedance. Just like a (roughly) 10MΩ resistor to ground. Very very little current will flow that way.
D2 is also reverse biased so that direction can be ignored.
So the current will want to flow through D1 to the VCC rail (+5V).  The diodes have approximately a 600mV forward voltage (which is where the VCC + 0.5 comes from).
So we can recalculate, given those parameters, what the current flowing through the diode will be to the 5V rail:

Voltage difference = 12V - 5V - 0.5V = 6.5V
Current = V/R = 6.5/330 = 19.7mA

The recommended maximum (from what I can gather) is only 1mA.  You have 20x that.
So you will need at least 20x higher resistances. 10kΩ in the upper half and 6.8kΩ in the bottom half.  That will give you 4.85V on the output at 12V and limit you to 0.65mA in a failure situation.
It also gives you an output impedance of a little over 4kΩ which is below the recommended maximum of 10kΩ for the ADC input.
You can further protect your input by adding a 5V zener diode and small series resistor on the ADC pin so if the voltage goes above 5V it clamps it and protects the pin.

simulate this circuit

The current will want to flow through D1 to the 5V rail? What? The voltage to be sampled needs to be between 0 and VCC (5V). If it's lower than 5V, won't D1 be reverse-biased and the potential will be applied to the ADC (which is a capacitor, if I remember correctly)

I thought that as long as you stayed within your voltage limits, the ADC was a capacitive input?

Oh, I see. I read the OPs question more carefully. He's looking to avoid destroying the input if the ground side of his voltage divider is left open and he pumps 12V into the pin. Yeah, wouldn't a 5V zener diode we the way to go?

@DuncanC Belt and braces. Keep the current < 1mA and add the zener. If one fails the other protects.


text:
Arduino Uno outputs 8V when pin is set to HIGH
I am doing the following in setup:
 pinMode(13,OUTPUT);
 digitalWrite(13, HIGH);

When I check with the multimeter, I get an output voltage of 8V rather than 5V. What may be the problem and how do I troubleshoot it?.

You have a badly calibrated multimeter? Try it on something where you know what the voltage should be, such as a 9V battery and see what it reads.

@Majenko : You were right. My DMM battery is low, hence its showing some wrong values :). I will replace it with a new one.

Is the code as shown what you actually have?  pinMode(13, HIGH); is invalid.  Perhaps you meant digitalWrite(13, HIGH);

You need to show more code. Your posted code doesn't do a digitalWrite, and even if it did, if it wrote HIGH and then LOW in quick succession you may get an unexpected reading.

You have a badly calibrated multimeter.
Try it on something where you know what the voltage should be, such as a 9V battery and see what it reads.

Yes, the meter should be suspect, but, I'd expect a "9v" battery to read anything from zero to close to ten volts with a calibrated meter, depending on chemistry, cell count, and condition.  Probably better to measure the circuit's supply and describe its source.

@ChrisStratton Yes, but if it is the multimeter at fault then I'd expect the 9V battery to read something like 12V or more to be inline with what the Arduino is measuring at. That can't happen with a 9V battery no matter how much charge it has left.


text:
Assigning value to a struct byte order
So i have struct:
typedef struct sendPacketStruct {
  byte header = headerByte;//0x55
  unsigned int time;//2 bytes
  int height;//2 bytes
};

And i do this:
    sendPacketStruct sendPacket;

    sendPacket.time = 84;//0x54
    sendPacket.height = 100;//0x65

    Serial.write((byte*)&sendPacket, sizeof(sendPacket));

But when i receive it at the other end the hex bytes are:
55 54 00 64 00
So the first byte is correct as the header 0x55, but the 2x 2 byte values time and height are there but shifted.
eg it should be 00 54 not 54 00

it should be 00 54 not 54 00 ... why? ... is it causing a problem? ... the bytes are not shifted

Because if i read out the 2nd and 3rd byte to make the int I would get 0x5400 which is 21504  not 84 (0x54)

see 'endiannes' in wikipedia. this is why it is better to send text between systems.

read out the 2nd and 3rd byte to make the int ... how are you making the int? ... are you reading the bytes separately?

I would be reading the serial data a byte at a time as that arrive into an buffer array. When I detect a full packet in the buffer I would convert the various bits into the data. This is in a mobile app.

OK so it's actually acting correct for a little endian system, which I didn't know it was, I'm just only experienced in big endian network protocols. Thanks @Juraj

Either agree on an endian-ness (for transmission) among all systems sharing this data, or include an endian-ness indicator in the packet, and all receiver's agree to receive accept either one.

Note that today most CPUs, including AVR, ARM and x86-64, are little endian.

The answer is that arduino is little endian, so the byte order is correct. I was just expecting big endian order as ive seen in some other network protocols. If that is desired instead I can just do some bit shifting and re-arranging.

The endianness of a protocol is defined by the protocol. In C there are functions htons() ntohs() etc for "Host to Network Short" and so on that set the correct endianness for the protocol.


text:
Barebones 328p, 2xAA vs 3xAA, which will last longer?
So im just running a 328p at 8mhz with the internal oscillator. Datasheet says 1.8 to 5.5v is voltage range.
Will 3xAA in series (~4.5v) last longer than 2xAA in series (~3v), assuming all batteries have the same capacity, theoretically each option should have the same mAh but does the difference in voltage affect things ?

Yes, running at a higher voltage will consume more current.  In the datasheet you have this nice graph:

I have highlighted the two voltages at 8MHz for you. At 4.5V you would typically be using about 4.7mA.  At 3V you would be using around 2.8mA.  That's not taking into account anything else in your circuit of course - just the ATMega itself.

thank you for pointing this out, yes its just the atmega im talking about.

Majenko's answer is correct, however he (or both of you) are assuming that the processor clock is running. When it runs, a processor cycle at a higher voltage will use more current. However when in power-down sleep mode the clock stops, and consumption is much lower. If you don't need the watchdog timer (for example, a switch closure activates the processor) then the difference will be negligible. Indeed, the current consumption is around 100 nA.

If you need the watchdog to periodically wake you, then the difference will be about 2 µA (that's a lot less than 2.8 mA).

These are quoted at room temperature - around 25°C.

I would be concerned about 2 x AA batteries. Their nominal voltage might be 3V, but their actual voltage (say, if they are NiMh batteries) might be closer to 2.4V, and that is the minimal amount for running at 8 MHz.
With 3 x AA batteries you are much more safely in range for the voltage requirements, particularly if you have some peripherals that might drain power, and thus lower the voltage.

Other discussions about low-power considerations at http://www.gammon.com.au/power.


text:
Communicate with custom usb slave device with DUE?
I have a arduino due which i know has usb host mode. The usb library that comes with the due supports mouse and keyboard.
I have another usb device (diacnostic tool) id like to talk to, it use a:
USB Com Board Driver ( Multi-instance )
TI USBN9604
"Universal Serial Bus Full Speed Node Controller with
Enhanced DMA Support"
datasheet: www.ti.com/lit/ds/symlink/usbn9603.pdf
Ive also logged the raw byte usb traffic between windows and it when operating and would like to try sending some of those same calls to the device with the due.
Where do i start ?
Example Capture:
    000000: PnP Event: Device Connected (UP), 12.04.2015 09:14:51.390 (1. Device: USB Com Board Driver ( Multi-instance ))
The USB device has just been connected to the system.
000001: Bulk or Interrupt Transfer (DOWN), 12.04.2015 09:15:14.953 +23.562 (1. Device: USB Com Board Driver ( Multi-instance ))
Pipe Handle: 0x8639885c (Endpoint Address: 0x6)
Send 0x1b bytes to the device
 40 05 17 C0 00 09 02 00 AA 00 00 00 00 00 00 00
 00 00 00 00 00 00 00 00 16 06 12

i found what i needed here: http://arduino.cc/en/Reference/USBHost
and
https://github.com/felis/USB_Host_Shield_2.0


text:
32u4 timer 4 pwm frequency help
I have extracted the following code from the multiwii project. It generates a ~490-500hz pwm signal on pin 6 which is used to drive an esc.
I want to change this frequency down to 50Hz to drive a servo instead. But ive had next to no experience at this level of avr programming, and dont want to loose anymore days to it, if its a dead end. (ie not possible) (i have tried reading various websites on the topic)
void setup() {
    pinMode(6, OUTPUT);
    TCCR4E |= (1<<ENHC4); // enhanced pwm mode
    TCCR4B &= ~(1<<CS41); TCCR4B |= (1<<CS42)|(1<<CS40); // prescaler to 16
    TCCR4D |= (1<<WGM40); TC4H = 0x3; OCR4C = 0xFF; // phase and frequency correct mode & top to 1023 but with enhanced pwm mode we have 2047

    TCCR4C |= (1<<COM4D1)|(1<<PWM4D); // connect pin 6 to timer 4 channel D

}

void loop() {
    //write out
    int value = 1500;
    TC4H = value>>8;
    OCR4D = (value&0xFF);
}

here is the new code so far working off the solution provided below:
void setup() {
    pinMode(6, OUTPUT);
    TCCR4B &= ~(_BV(CS43) | _BV(CS42) | _BV(CS41) | _BV(CS40));
    TCCR4B |= _BV(CS43) | _BV(CS41);
    TCCR4D &= ~(_BV(WGM41) | _BV(WGM40));
    TC4H = 624 >> 8; // B10 0x2
    OCR4C = 624 & 0xff;//B1110000 0x70
    TCCR4C |= (1<<COM4D1)|(1<<PWM4D);
}
void loop() {
    //write out
    //30 - 60 gives 1000 to 2000 us, but that only allows 30 increments between ??
    int value = 30;
    TC4H = value >> 8;
    OCR4D = value & 0xff;
}

the wave form i want:

Yeah... sometimes it's easier to scrap what's already there and start fresh.
We need to:

Pick a suitable prescaler to get close to the desired cycle length
Fine-tune the value in TOP in order to get an exact value

Assuming this is a 16MHz Leonardo, and we have Fast 10-bit PWM (PWM4x = 1, WGM4x = 0b00) available:
16MHz / 50Hz / (1 << 10) = 312.5
Therefore we need a prescaler of 512 (CS4x = 0b1010).
16MHz / 50Hz / 512 = 625
Therefore we need a TOP of 624 (OCR4C = 624).
TCCR4B &= ~(_BV(CS43) | _BV(CS42) | _BV(CS41) | _BV(CS40));
TCCR4B |= _BV(CS43) | _BV(CS41);
TCCR4D &= ~(_BV(WGM41) | _BV(WGM40));
TC4H = 624 >> 8;
OCR4C = 624 & 0xff;

And then you set COM4xn and PWM4x to appropriate values for whichever pin(s) you want to output PWM on, and set OCR4x to a value between 0 and 624 (using TC4H appropriately; see the datasheet for details) to control the duty cycle.

ok, its working but i think we 'overlooked' something important i forgot to mention... i need the duty cycle to suit a servo, so between 1 and 2 milliseconds. the duty im getting from your example is much bigger 2ms to 19.2 ms its like 10x too much, maybe we dropped a decimal ? (but the frequency is correct)

ive added the code i have put together from your help above into the question. if i use a value between 30 and 60 it gives me the correct duty, but this only allows 30 steps .. ?

@HaydenThring: 50Hz means a 20ms period. If that's too long then use a higher frequency. The Arduino libraries use 490Hz.

i have added a screenshot of the waveform i want, it needs to be 50hz, which is what im getting from your code, but there is a lack of resolution in the settable values to get that duty.

@HaydenThring: If you need that resolution at that low a frequency then you'll need to use timer 1 or 3 instead, in wavegen mode 14.

firstly thanks again for your reply. i thought this might be the situation, as the code they use to generate the 50hz on the other pins uses those timers and is markedly different. i will add it to my question for reference, (though i have not got it working, its all the related code to it i can find to extract)

To get finer resolution use Timer 1 - as Ignacio Vazquez-Abrams suggested.
void setup ()
  {
  pinMode (10, OUTPUT);   // OC1B on the Leonardo / Micro
  TCCR1A = 0;   // stop Timer 1
  TCCR1B = 0;   //     ditto

  // set up Timer 1
  TCCR1A = bit (COM1B1) | bit (WGM11) | bit (WGM10);  // toggle OC1B on Compare Match
  TCCR1B = bit (WGM13) | bit (CS11);   // PWM phase correct, prescaler of 8
  OCR1A = 20000;  // frequency: 50 Hz
  OCR1B = 1000;   // duty cycle - 1 ms
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

As you can see from the scope output, the pulse width is 1 ms, which extremely conveniently corresponds to the duty cycle of 1000. Thus, therefore, the duty cycle figure is exactly related to microseconds.
Also you can see that the frequency is 50 Hz.

This uses a prescaler of 8 to give high resolution. It takes two pulses to make one "cycle" (one on, one off) and thus it effectively divides the system clock by 16. Since the system clock is 16 MHz, that is why one "unit" is 1 µs.
The OCR1A figure is arrived at easily:
 1000000 / 50 = 20000  (1 MHz / 50 Hz)

Now you can just tweak your desired pulse width knowing that each unit is 1 µs. So for 2 ms OCR1B would need to be 2000.

I cant use this on pin D6 though can i ?

On the arduino micro can i use 3 pins using this code? if yes which ones?

@HaydenThring - nope, you cant use D6 for this if you are not using Timer 1 as suggested


text:
Crosses Initialization in switch case with different size of array per case
void setup()  {
 Serial.begin(9600);
}

void loop()
{
 time_Text(2);
}

void time_Text(int PastTo_val) {
  switch (PastTo_val) {
   case 1:
   {
    int tPTT_y[] = {11, 11, 11, 11};
    int tPTT_x[] = {6, 7, 8, 9};
  }
  break;
case 2:
  {
    int tPTT_y[] = {11, 11};
    int tPTT_x[] = {10, 11};
  }
  break;
 }

 int n_tPTT = sizeof(tPTT_x) / sizeof(tPTT_x[0]);

 Serial.print(tPPT_y);
 Serial.print(" : ");
 Serial.print(tPPT_x);
 Serial.print(" : ");
 Serial.println(n_tPPT);

}

I have a case that I need to assign different kind of array value (with different size per case), and then find the size of the array, and print it. The problem is that the tPTT_y and tPTT_x is a local variable which cannot be accessed outside of the case function. I have tried to declare it before the switch function but I cannot give a size number because the size is different per case, how could I solve this?

Create two global arrays that contain the maximum amount of number you ever need, e.g.
int tPTT_x[4];
int tPTT_y[4];

Than create one global int that contains how much x and y are filled, e.g.
int filled;

Than you can change your cases to
void time_Text(int PastTo_val) {
  switch (PastTo_val) {
   case 1:
   {
    tPTT_y[0] = 11;
    tPTT_y[1] = 11;
    tPTT_y[2] = 11;
    tPTT_y[3] = 11;
    tPTT_x[0] = 6;
    tPTT_x[1] = 7;
    tPTT_x[2] = 8;
    tPTT_x[3] = 9;
    filled = 4;
  }
  break;
case 2:
  {
    tPTT_y[0] = 11;
    tPTT_y[1] = 11;
    tPTT_x[0] = 10;
    tPTT_x[1] = 11;
    filled = 2;
  }
  break;
 }

Than you can use the 'filled' variable to see how many items in the array are 'valid' (0 <= item < filled).

@MaximilianGerhardt Thanks for the remark (don't have a compiler at hand). I fixed it in my answer.

Just create a buffer of a maximum value and copy in the value you want while remembering the length of the array.
#define MAX_ARR_LENGTH (4)

void time_Text(int PastTo_val) {
    int tPTT_x[MAX_ARR_LENGTH];
    int tPTT_y[MAX_ARR_LENGTH];

    const int tptt_y_case_1[] = {11, 11, 11, 11};
    const int tptt_x_case_1[] = {6, 7, 8, 9};
    const int tptt_y_case_2[] = {11, 11};
    const int tptt_x_case_2[] = {10, 11};

    int filled = 0;

    switch (PastTo_val) {
    case 1:
    {
        memcpy(tPTT_x, tptt_x_case_1, sizeof(tptt_x_case_1));
        memcpy(tPTT_y, tptt_y_case_1, sizeof(tptt_y_case_1));
        filled = 4;
    }
    break;
    case 2:
    {
        memcpy(tPTT_x, tptt_x_case_2, sizeof(tptt_x_case_2));
        memcpy(tPTT_y, tptt_y_case_2, sizeof(tptt_y_case_2));
        filled = 2;
    }
    break;
    }

    Serial.println("Printing array values");
    for(int i=0; i < filled; i++) {
        Serial.println("tPPT_x["+ String(i) +"] = " + String(tPTT_x[i]));
        Serial.println("tPPT_y["+ String(i) +"] = " + String(tPTT_y[i]));
    }
}

Depending on whether you need to modify the memory you can also just point to constant memory and remember the length.
void time_Text(int PastTo_val) {
    const int* tPTT_x;  //Pointers to the values
    const int* tPTT_y;

    //You make also add "static" if you want to reference this
    //data beyond the scope of the function
    const int tptt_y_case_1[] = {11, 11, 11, 11};
    const int tptt_x_case_1[] = {6, 7, 8, 9};
    const int tptt_y_case_2[] = {11, 11};
    const int tptt_x_case_2[] = {10, 11};

    int filled = 0; //number of elements

    switch (PastTo_val) {
    case 1:
    {
        tPTT_x = (const int*) tptt_x_case_1;
        tPTT_y = (const int*) tptt_y_case_1;
        filled = 4;
    }
    break;
    case 2:
    {
        tPTT_x = (const int*) tptt_x_case_2;
        tPTT_y = (const int*) tptt_y_case_2;
        filled = 2;
    }
    break;
    }

    Serial.println("Printing array values");
    for(int i=0; i < filled; i++) {
        Serial.println("tPPT_x["+ String(i) +"] = " + String(tPTT_x[i]));
        Serial.println("tPPT_y["+ String(i) +"] = " + String(tPTT_y[i]));
    }
}


text:
Problem in bootloading my ATmega32U4 chip
I have developed my own development board using ATmega32U4. I want to bootload my ATmega32U4 and hence I used Arduino Uno to bootload it. I have given the connections as per
https://www.arduino.cc/en/Tutorial/ArduinoISP
 and I followed this instructions:

Open the ArduinoISP firmware (in Examples) to your Arduino board.
Select the items in the Tools > Board and Serial Port menus that correspond to the board you are using as the programmer (not the board being programmed).
Upload the ArduinoISP sketch.
Wire your Arduino boards..
Select the item in the Tools > Board menu that corresponds to the board on which you want to burn the bootloader (not the board that you're using as the programmer). See the board descriptions on the environment page for details.
Select the Arduino as ISP in the Tools>Programmer menu.
Use the Burn Bootloader command.

But I am getting the error message as
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

I am using 16Mhz crytsal oscillator along with 22pf
What might be the problem?

Did you include the 10uF capacitor?

If you are developing your own board there are a number of things which can go wrong, although the problem is usually very simple and bootloading will be easy once you fix the bugs.
Possible hardware problems are:

You have bad solder joints / connections.  Even if you think the solder joints are good, try reflowing them again
ISP leads are too long - can lead to data corruption during bootloading
Pins are not correct.  E.g. are MOSI and MISO the correct way around?
Reset pin needs a pullup resistor

Most likely, you have some sort of hardware problem.  Post your board layout (or at least schematic) and we can look at it.  If you have a pro micro board to hand (if not, buy one one ebay or similar), try bootloading that and see whether your procedure works.

tanq...I will do your suggestions


text:
Combining arduino leonardo code with water alarm code
I need to create something for a school assignment, but I'm stuck at the moment.
I have one code, which makes the Arduino Leonardo press space button on my laptop, which works.
I have another code, that turns on the LED when 2 wires are put in water.
Now I want to combine them, but I have no success.
Hope someone will help me with this.
These are the codes:
The keyboard code leonardo:
bool eenkeergeweest = false;

#include <Keyboard.h>

void setup()
{
    // make pin 2 an input and turn on the
    // pullup resistor so it goes high unless
    // connected to ground:
    pinMode(2, INPUT_PULLUP);
    // initialize control over the keyboard:
    Keyboard.begin();
}

void loop()
{
    // while (digitalRead(2) == HIGH) {
    //   // do nothing until pin 2 goes low
    //   delay(500);
    //  }
    delay(1000);
    // new document:
    if (!eenkeergeweest) {
        eenkeergeweest = true;
        Keyboard.print(' ');
        delay(100);
        //Keyboard.releaseAll();
    }

    // wait for new window to open:
    delay(1000);
}

The code for the water LED:
int out = 12;
int in = 4;

int rd;

void setup()
{
    pinMode(out, OUTPUT);
    pinMode(in, INPUT);
}

void loop()
{
    rd = digitalRead(in);
    if (rd == HIGH)
    {
        digitalWrite(out, HIGH);
        delay(100);
    }
    else
    {
        digitalWrite(out, LOW);
        delay(100);
    }
}

Arduino IDE has a KeyboardMessage example. Did you look at it?

I you only want the space to be pressed once, you could just place the code in setup. But it's unclear what you want the combined code to do.

Thanks for the help but Matt allready fixed the problem.

How do you want them to work ? Do you want the spacebar pressed when there is a high signal read (when the light goes on)?
If you want the space bar press when it goes high this might work:
#include <Keyboard.h>

bool eenkeergeweest = false;
int out = 12;
int in = 4;

void toggleKeyPress (const char& keypress)
{
    if (!eenkeergeweest)
    {
        eenkeergeweest = true;
        Keyboard.print(' ');
        delay(100);
    }
}

void setup()
{
    pinMode(out, OUTPUT);
    pinMode(in, INPUT);

    // initialize control over the keyboard:
    Keyboard.begin();

}

void loop()
{
    const int rd = digitalRead(in);
    if (rd == HIGH)
    {
        toggleKeyPress(' ');
        digitalWrite(out, HIGH);
        // wait for new window to open:
        delay(1000);
    }
    else
    {
        digitalWrite(out, LOW);
    }
}


text:
Output works on UNO Pin 13, but not on 2?
I am experimenting with IR receive and transmit (basically I want my IOT to be able to turn on the TV, satellite receiver, and set the channel - yes, I am really that lazy).
I can receive and record the remote codes, and I can transmit the codes to an IR LED.
Now for the puzzle. I originally had my IR LED on Pin 13, but to clean things up I moved the output to pin 2 and changed the pin assignment in the sketch. Now it doesn't work. My phone camera shows that the IR LED is pulsing as before, but the appliance code is not working. Moving back to pin 13 and it works again.
So, what could be different between pins 13 or 2? I know that Pin 13 has the built-in LED but since I am setting it to output that shouldn't make a difference.
I am bit-banging to create the 38kHz pulses to the IR LED, so I am wondering if there is a latency difference from pins 2 and 13?
The sketch, since I know someone will ask for it:
int IRledPin =  13;
int buttonPin = 4;

void setup()   {
  pinMode(IRledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(buttonPin, HIGH); // pullup
  Serial.begin(115200);
}

void loop()
{
  if (! digitalRead(buttonPin)) {
    // button down
    Serial.println("Sending IR signal");
    SendCode();
  }
}

// This procedure sends a 38KHz pulse to the IRledPin
// for a # of microseconds.
void pulseIR(long microsecs) {
  // we'll count down from the number of microseconds we are told to wait

  cli();  // this turns off any background interrupts
  while (microsecs > 0) {
    // 38 kHz is about 13 microseconds high and 13 microseconds low
    digitalWrite(IRledPin, HIGH);  // this takes about 3 microseconds
    delayMicroseconds(10);         // hang out for 10 microseconds
    digitalWrite(IRledPin, LOW);   // this also takes about 3 microseconds
    delayMicroseconds(10);         // hang out for 10 microseconds
    // so 26 microseconds altogether

    microsecs -= 26;
  }
  sei();  // this turns interrupts back on
}

void SendCode() {
  // This is the code for my FIOS FF
Serial.println("FIOS- FFwd");
  pulseIR(9220);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(22320);
  pulseIR(9200);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2260);
  pulseIR(520);

}

Maybe a trivial remark, but did you change the first line: int IRledPin =  13;  to value 2?

For equivalence checking, you would need to get a logic analyzer and measure the pin signals for your D13 and D2 version. If those are exactly equivalent (and the current leaving that pin, too), I wouldn't know what else makes a difference. You could check what signal it decodes to using a standard IR decoder (http://www.instructables.com/id/Arduino-Infrared-Remote-tutorial/) just to make sure, too.

 void SendCode() {
  // This is the code for my FIOS FF
  Serial.println("FIOS- FFwd");
  pulseIR(9220);
  delayMicroseconds(4540);

Personally I would be putting the cli() around everything in SendCode (apart from the Serial.println) because the serial print will cause interrupts, and they could occur between successive function calls there.
I checked your code using IDE 1.6.9 and got this pulse width for pin 2:

And this pulse width on pin 13:

You'll notice they are virtually identical and that neither show a frequency of 38 kHz. The measured period of 30.71 µs gives a frequency of 32.563 kHz.
Unless your version of the compiler generates different code than mine, I suggest you need to tweak your timing loops.

I am wondering if there is a latency difference from pins 2 and 13?

No, I think not. The problem may be elsewhere, such as electrical. I suggest you try to measure the frequency of your timing loops using whatever external equipment you have to hand. For example, just call your pulseIR function constantly and measure with a frequency meter. I measured 32.555 kHz on my meter, for example.

Use a timer to generate 38 kHz
You will get a more accurate 38 kHz signal if you use the hardware timers, properly configured. For example:
const byte LED = 10;  // Timer 1 "B" output: OC1B
const byte buttonPin = 4;

// Clock frequency divided by 38 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 38000L;

void setup()   {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode (LED, OUTPUT);
  Serial.begin(115200);

  // set up Timer 1 - gives us 38.005 kHz
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11);                // fast PWM
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  OCR1B =  timer1_OCR1A_Setting / 2 - 1;             // duty cycle
}

void loop()
{
 if (! digitalRead(buttonPin)) {
    // button down
    Serial.println("Sending IR signal");
    SendCode();
    delay (200);
  }
}

// This procedure sends a 38KHz pulse to the IRledPin
// for a # of microseconds.
void pulseIR(const unsigned int microsecs) {
  TCCR1A |= bit (COM1B1); // clear OC1B on compare
  delayMicroseconds (microsecs);
  TCCR1A &= ~bit (COM1B1); // don't clear OC1B on compare
  digitalWrite (LED, LOW);
}

void SendCode() {
  // This is the code for my FIOS FF
  Serial.println("FIOS- FFwd");
  noInterrupts ();
  pulseIR(9220);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(22320);
  pulseIR(9200);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2260);
  pulseIR(520);
  interrupts ();
}

This sets up Timer 1 to output 38 kHz, and then for the timing of the pulses you just turn its output on and off.
Note that you have to use D10 on your Uno because that is where Timer 1 outputs to.

For more information see my page about timers.
I have a graphic which shows a lot of the useful registers:

I know I am not supposed to say thanks here, but you have gotten me back into the books for the past two days to learn something about the Atmel chip timers.  (I hate to blindly copy code without knowing how it works).  So, if I understand correctly, Timer1 is in a free-run at 38 kHz.  The output pin is enabled with TCCR1A |= bit (COM1B1) and disabled with TCCR1A &= ~bit (COM1B1).  Do I have this right?

That's right, I've amended the answer to have a link to my page about timers, and a graphic showing various registers. With appropriate values in OCR1A and OCR1B you can set a frequency and duty cycle. In my case I made the duty cycle 50%.


text:
Wired IoT sensor network with PoE?
Objective: Maybe I'm a bad Googler, but I am finding very little on wired Internet of Things sensor networks using Arduino.
Project Goals:

Arduino based sensor nodes that connect to the local network (not out to the internet)
All the benefits of adding adding/removing nodes, moving nodes, adding new routers for more ports.
Black box sensors that don't take any soldering to plug into the network (although they contain soldered components in the black box.
Using a master Raspberry Pi on the network to identify the nodes and read data from them.
Using Power over Ethernet (PoE) to power my sensor nodes.
Don't want to actually connect to the outside internet, just want the convenience of assembling a network with node names and such.

Why not use wireless solutions (e.g. XBee):
Currently, it seems Xbee is the way to go, but I don't want a wireless solution.

I want the reliability of a wired connection.
I don't want to have to worry about batteries

What I'm doing right now:
Currently, I have all my sensors wired to a central Arduino MEGA using 4-conductor security cable (Vcc, GND, and two signal conductors). The MEGA communicates over serial with a Raspberry Pi. This is annoying for the following reasons:

I have to solder/unsolder every time I want to change something.
I have to figure out which digital I/O pins are available on the MEGA and have to write down which signal conductor goes to which pin on the MEGA and means what on the sensor.
There is a finite number of pins.
Each sensor is its own unique project. I want to start standardizing these sensors to clean up the code.

What I have found so far:
I've been looking at XPort sensors; however they are very expensive (i.e. $60 ea.) and don't support PoE. If there is a solution using Arduino and an Ethernet Shield, it brings down the base cost of a sensor by a lot.
Request:
Where can I find out more information about wired Arduino sensors? Are there any prebuilt solutions that already do what I am looking for?

Since you don't want to connect to the internet, you could just use any protocol over those ethernet cables (they are just copper wires). Something like RS485.

I was hoping to be able to use pre-existing equipment to handle some of the work for me (i.e. add new ports by adding routers/switches, having them assign new addresses automatically).

MySensors.org supports RS485, while qualifying as an IoT platform. It might be worthwhile to consider ethernet<->serial gateways.

I think I am using a setup like you wish at my home:

PoE Switch (for example Cisco SG300-28P)
Arduino Ethernet's with PoE Module (https://www.arduino.cc/en/Main/ArduinoBoardEthernet) I bought one for every room ;-)
Use DHCP-Server on raspberry PI
Put your sensors on your Arduino ethernet board
I am also using MQTT as protokoll for example http://pubsubclient.knolleary.net/
Use MQTT broker Mosquitto on raspberry pi

For the case that you want to use your switch also for internet connectivity, define a vlan (search wikipedia) for your arduino sensor network.
Hope that helps.

I'm curious how/where you bought the Arduino PoE modules.  Everywhere I look they're "retired" and unavailable.

Because I am located in Germany, I bought them at:
Watterott.com also Exp-Tech.de has them available (at the moment ;-) It is no problem to solder the PoE Modules yourself into ethernet shields.

Ah, yes I have seen those modules here in the US as well that you can add to the Ethernet shield, it just seemed rather costly ($13 for the module + ~$30 for the shield + the arduino cost itself).  I managed to find a complete PoE shield on ebay for $20 but that was a one time deal and I'd like to build several.  Thanks for the help.

Enviromon.net has PoE sensors that are plug and play with their base units. The base unit is then connected to your internal network.
If your a bit more experienced (which it seems you are) their base units can also be integrated into other systems like network monitoring apps, and SCADA programs.
You could most likely configure the base unit to slave to your raspberry pi, and bonus, no soldering. All their sensors are PoE. Although unfortunately they are not for the Arduino.
But you mentioned if anyone knew if there was a prebuilt solution.
Heres a link to their sensors you might be interested in http://www.enviromon.net/environmental-monitoring-sensors/

Please note if you want to promote your own product/blog you must disclose your affiliation in the answer, otherwise your answer may be flagged as spam. Please read How to not be a spammer

If you are not affiliated with the site, I recommend you mention it to prevent this.


text:
Cascaded Control loop Arduino
I am trying to implement cascaded control system, with velocity inner loop and position outer loop.
Separately and without cascaded control, I have implemented position control and velocity control easily, thanks to the "pid library."
I have no idea how to convert position output from position pid to reference velocity.
Any help would be appreciated, since I am blank on this topic.
Thanks and best regards

This is not an Arduino specific topic, but here is just a pragmatic answer:
Use the output of the PID controller directly as your reference velocity, subtract your actual velocity and use it as input for the PID velocity. Units do not care in this case.
You have to make sure that the paramters of your PID position are well adjusted, this will set the problem with the units.
Here is an example to understand (only P gain considered):
If you want to drive from A to B with your car and the distance from A to B is 10 km, then your desired position is 10km and i would choose to drive about 100km/h. So in this example you start with a control deviation of 10km - 0km = 10km. If you choose a P gain of 10 the output of the PID will be 100, which is an ideal refernce Velocity, if velocity is given in km/h.
But if you are measuring your distance not in km but in m, the control deviation will be (10.000m - 0m = 10.000m), with a P gain of 10 you will end up with a refernce velocity of 100.000km/h, which is not an appropriate reference velocity in this case.
Now someone may object that in my example if you want do drive from A to C and C is 1.000km away, you will end up with an reference velocity of 10.000km/h, which is also not appropriate, but that is where the limitations in a PID controller are usefull, just set them for this example to 130km/h and you will end up stil with an appropriate reference velocity, and also your integrator part will not wind up endlessly.
You can look at I and D gain in a similar manner.

Yeah I got it thanks

@SyedTirmizi you are welcome, I hope your system works. :-)


text:
Where can I find the source codes for the various classes and methods used in Arduino Primo?
I am new to Arduino development. I am trying to connect a BLE device (Arduino Primo) with my iOS app. From the Arduino BLE examples, I understand how to initialize the BLEperipheral class and then call the setValue method to pass value to be transmitted. However I do not want to be dependent on example codes, rather I want read the source code and definitions to know about the available classes and their methods, what argument types passed etc.(not precompiled libraries with .o extension).
For my current issue, I want to know what type of arguments does the setValue take in the BLEperipheral class. Can I pass an int value(4 bytes) or it has to be a char only? These questions can be answered by reading the source code of these inbuilt libraries.
Any direction would not only help me with the current project, it would also help to tackle and understand any projects in the future, where I might use inbuilt library calls.
I have searched the internet, however not much information is available for newcomers like me.
Below is a similar question link but outdated and does not solve what I am looking for.
How can I get the source files for Arduino libraries?
Thank you for any suggestions.

you have them on your computer in arduino15 folder

Sir, i have checked all the folders in my computer and even my neighbours computer too. hehe. There is no such folder called ardunio15 nor any reference to the information i am looking for.

The Arduino Primo is supported by Arduino nRF52 boards package. The boards packages can contain libraries special for boards handled by the package. The BLE library for Arduino Primo is included in the board package.
The location of boards packages on Windows is in hidden folder AppData in user's home directory. On my Windows computer it is
C:\Users\andrassy\AppData\Local\Arduino15\packages\arduino\hardware\nrf52\1.0.2\libraries\BLE

On Linux the 'Arduino 1.5' folder is .arduino15 in users home folder.


text:
Processing error with processing-arduino examples
I have followed the instructions to run the Arduino processing examples but with no success.
Always import processing.serial.*; does not name a type. Which is perhaps a library (processing-arduino) related error.
My sketch is a sketch that comes with processing-arduino library.
I have searched for a long time with no solution. Any suggestion?
Errors:
arduino_output:28: error: 'import' does not name a type
arduino_output:30: error: 'import' does not name a type
arduino_output:32: error: 'Arduino' does not name a type
arduino_output:34: error: 'color' does not name a type
arduino_output:35: error: 'color' does not name a type
arduino_output:37: error: expected unqualified-id before '[' token
arduino_output.pde: In function 'void setup()':
arduino_output:42: error: 'size' was not declared in this scope
arduino_output:45: error: 'Arduino' was not declared in this scope
arduino_output:45: error: 'println' was not declared in this scope
arduino_output:50: error: 'arduino' was not declared in this scope
arduino_output:50: error: expected type-specifier before 'Arduino'
arduino_output:50: error: expected `;' before 'Arduino'
arduino_output:58: error: expected unqualified-id before numeric constant
arduino_output.pde: In function 'void draw()':
arduino_output:62: error: 'off' was not declared in this scope
arduino_output:62: error: 'background' was not declared in this scope
arduino_output:63: error: 'on' was not declared in this scope
arduino_output:63: error: 'stroke' was not declared in this scope
arduino_output:66: error: 'values' was not declared in this scope
arduino_output:66: error: 'Arduino' was not declared in this scope
arduino_output:66: error: expected unqualified-id before numeric constant
arduino_output:66: error: expected `)' before numeric constant
arduino_output:67: error: 'fill' was not declared in this scope
arduino_output:69: error: 'fill' was not declared in this scope
arduino_output:71: error: 'rect' was not declared in this scope
arduino_output.pde: In function 'void mousePressed()':
arduino_output:77: error: 'mouseX' was not declared in this scope
arduino_output:80: error: 'values' was not declared in this scope
arduino_output:80: error: 'Arduino' was not declared in this scope
arduino_output:80: error: expected unqualified-id before numeric constant
arduino_output:80: error: expected `)' before numeric constant
arduino_output:81: error: 'arduino' was not declared in this scope
arduino_output:81: error: expected unqualified-id before numeric constant
arduino_output:82: error: expected unqualified-id before numeric constant
arduino_output:82: error: expected `;' before numeric constant
arduino_output:84: error: 'arduino' was not declared in this scope
arduino_output:84: error: expected unqualified-id before numeric constant
arduino_output:85: error: expected unqualified-id before numeric constant
arduino_output:85: error: expected `;' before numeric constant

Welcome to Stack Exchange ibrahim. Can you edit your answer to include the example code? Is it the example that is near the bottom of the page that you link to? Also, you may like to take a tour of this site.

Which processing-arduino package version are you using, processing-arduino.zip or processing2-arduino.zip? Which version of the processing application are you using? Are you using it with the correct version of Processing?

Note: I am testing this on OS X, so my paths may differ slightly from yours.

I have managed to reproduce your issue, by incorrectly copying the arduino directory, from the unzipped processing2-arduino.zip package, to the libraries directory under the Arduino directory in my home directory, thus
/Users/user/Documents/Arduino/libraries/arduino

Then opening the Arduino IDE and running the arduino_output example, via the menu, File -> Sketchbook -> Libraries -> Arduino -> arduino_output. When I hit the compile button, in the Arduino IDE, the compiler throws up the exact same errors that you describe in your question.
However this is not the correct usage of this package. This package is intended to be used in conjunction with the Processing application, not the Arduino IDE. You should download Processing and then follow the instructions again:

Unzip the library and copy the "arduino" folder into the "libraries" sub-folder of your Processing Sketchbook. (You can find
  the location of your Sketchbook by opening the Processing Preferences.
  If you haven't made a "libraries" sub-folder, create one.)

Thus, on OS X, the path should now be
/Users/user/Documents/Processing/libraries/arduino

However, as usual, the documentation on the Arduino website leaves a lot to be desired. Pay careful attention to the following paragraph if you are running OS X or Linux:

Note: if you run Linux, you need to change Arduino.jar into
  arduino.jar, because Linux is case sensitive and it does not work if
  you don't change this letter (Arduino.jar is in the folder "library"
  of this Processing Library).

So,
/Users/user/Documents/Arduino/libraries/arduino/library/Arduino.jar

becomes
/Users/user/Documents/Arduino/libraries/arduino/library/arduino.jar

Relaunch the Processing application. File -> Examples..., opens up a window, scroll down to Contributed Libraries, open that, open Arduino (Firmata), open the arduino_output example. Hit the Run button, and after compiling you should see the window below:

HTH.


text:
LininoIO running "partially"
I installed LininoIO (OS dated 02 06 2015).
Everything seems to work fine - but nothing works as expected.
I have a running Linux - but when I try to use GPIO, as described on Lilino.org -GPIO on lininoIO, I run into the first problems.
D13 doesn't exist (this should be the little red LED on board of the Yún).
Next I tested reading the analog inputs.
I can for example use cat /sys/bus/iio/devices/iio:device0/in_voltage_A0_raw. There are no errors, but I always get the value 0.
Checking with /etc/linino/test_avrdude.sh shows:
Testing AVRDUDE on ATMEL 32U4 ...

avrdude: Version 6.1-20140519, compiled on Jun  2 2015 at 12:34:59
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/root/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : unknown
         Using Programmer              : linuxgpio
Can't export GPIO 11, already exported/busy?: Device or resource busy
avrdude done.  Thank you.

Maybe this is "by design" or another sign of an error.
By the way - when I start a serial console I get the message:
avr-uart: switched to uart mode: mcuio

Further in kernel log I found:
[   42.480000] fuse init (API version 7.18)
[   42.620000] spi_tty_plain spi1.0: spi_tty_probe
[   45.380000] No need to change console settings
[   49.550000] mcuio-hc 0:0.0: unexpected reply
[   49.600000] gpiochip_add: registered GPIOs 100 to 139 on device: generic
[   49.630000] mcuio adc is 0:1:1
[   49.750000] mcuio-adc 0:1.1: 6 input channels detected
[   49.910000] mcuio-hc 0:0.0: unexpected reply
[   49.970000] mcuio pwm is 0:1:2
[   49.970000] mcuio-pwm 0:1.2: 6 pwm outputs detected
[   55.790000] busybox: sending ioctl 5310 to a partition!
[   55.800000] busybox: sending ioctl 5310 to a partition!
[   55.820000] busybox: sending ioctl 5310 to a partition!
[   55.830000] busybox: sending ioctl 5310 to a partition!
[   56.290000] EXT4-fs (sda2): couldn't mount as ext3 due to feature incompatibilities
[   56.310000] EXT4-fs (sda2): couldn't mount as ext2 due to feature incompatibilities
[   56.360000] EXT4-fs (sda2): mounted filesystem with ordered data mode. Opts: (null)
[   58.520000] cfg80211: Calling CRDA for country: AT

It seems as if there are problems with mcuio-hc.
Last thing - when I ran run-avrdude /etc/linino/bathos-one.hex
I get an error when comparing the written data (I found information that this can be ignored).
How can I fix this / find out what to fix / what's going wrong?

finally I got it (somehow) working.
After a reset and another run of run-avrdude /etc/linino/bathos-yun.hex (the first was a mistake by copy and past - not bathos-one I already ran bathos-yun before) and a reboot again I was able to read analog IO.
But still the digitals were missing.
Than I found the command gpioexport an ran it.
After that the correct entries (D13, D14...) were present in sys/class...
But an echo out > D13/direction resulted in a timeout error message.
Again reboot - again the Dxxx entries were gone.
Another gpioexport made them appear again.
And this time not timeouts - instead I could turn on / of D13 (for test).
I guess all I have to do to make the things better is include gpioexport in "startup code" so that it runs after a reboot.

LininoIO has a part which runs on the microcontroller and make the Atheros enable to use the mcu pinout as linux gpios. So you are right, you need to flash the bathos to the mcu.
In general to enable/disable lininoIO run:
> lininoio start
> lininoio stop

those commands do everything for you.
have also a look here
Anyway your Linino version seems old, try to upgrade it: http://www.arduino.org/learning/tutorials/advanced-guides/how-to-upgrade-the-linino-distribution-for-arduino-yun-and-yun-mini

Have a look at the schematics of the YUN https://www.arduino.cc/en/uploads/Main/arduino-Yun-schematic.pdf
You will notice that most of the GPIO pins on the Atheros is not available to you. You only have access to the GPIO pins of the atmega.

I know this fact. In my example I'm talking about the D13 which is as pin from the 32U4. And the bathos-yun.hex makes those pins available in linux. Something like using the bridge.

And as I wrote in my second post it finally works - with some little problems. That wouldn't be if I couldn't somehoe reach the pins from linux


text:
Unable to receive and print SMS on the serial monitor with Arduino Uno and SIM900A
I'm trying to receive an SMS and show it on the serial monitor.
My code is as following:
void setup()
{

  Serial.begin(2400);
  Serial.write("AT+CMGF=1\r");           //set GSM to text mode
  delay(1500);

  Serial.write("AT+CPMS=\"SM\"\r");         //Preferred SMS Message Storage
  delay(1000);

  Serial.write("AT+CMGL=\"ALL\"\r");       //List SMS Messages from Preferred Storage
  while(1)
  {
    if(Serial.available())
    {
      Serial.write(Serial.read());
    }
  }
}

void loop()
{
}

The circuit diagram is as shown below.

The output that I am getting is as following:
AT+CMGR=1
AT+CMGF=1

OK
AT+CPMS="SM"

ERROR
AT+CMGR=1
AT+CMGF=1

OK
AT+CPMS="SM"

ERROR

ERROR
AT+CMGR=1
AT+CMGF=1

I am not able to use AT+CPMS or AT+CMGL commands.

I put your code inside the code block exactly as it was. Please clean it up because there are extra curly braces.

Your output doesn't match your code.  The output says you are sending CMGR and CMGF in one line, but your code only sends CMGF.

Cleaned the code.

@JRE : please check the updated output.

ERROR SOLVED:For receiving SMS, 5V supply from arduino is insufficient , thus 12v 1 amp supply is required separately.I had faulty adapter, changed it and ERROR got resolved. Though still not able to read messages Because CPMS command  gives 0,20 that means 0 sms present and max memory is 20 SMS.PS: I have SMS stored on sim.

As others have stated, you cannot use the hardware serial port for communication with the device and communication over the USB cable.
OPTION 1
Switch to a different microcontroller, such as the arduino mega with multiple hardware serial ports on board.
OPTION 2
Implement the Software Serial library for communication with the sim card device and use the hardware serial for communication with your computer.
Note: Software Serial implementations are more computationally intensive than the use of hardware serial. Do not expect the same performance from a software serial implementation and do not expect to be able to smoothly run multiple instances of it on a single 8 bit mcu.
Example Code (Untested):
  #include <SoftwareSerial.h>

  void setup()
  {
  Serial.begin(9600);
  SoftwareSerial mySerial(10,11); //RX,TX pins
  mySerial.begin(2400);
  mySerial.write("AT+CMGF=1\r");           //set GSM to text mode
  delay(1500);

  mySerial.write("AT+CPMS=\"SM\"\r");         //Preferred SMS Message Storage
  delay(1000);

  mySerial.write("AT+CMGL=\"ALL\"\r");       //List SMS Messages from Preferred Storage
  while(1)
  {
    if(mySerial.available())
    {
      Serial.write(mySerial.read());
    }
  }
}

void loop(){}

Disconnect from pin 0 and pin 1 and connect to pins 10 and 11 respectively.

The Arduino UNO that you are using only supports one Serial connection (over the TX and RX pins). Since you are using these pins to talk to the device, you cannot also send data over Serial.
Read this article to see more about Serial and how it works on different boards.

So what is to be done as an alternative ?

@Ryhot I'm not sure, there isn't really much that you can do. You could look into getting an LCD display and then you could write the SMS messages to that. Or, alternatively you could just use a MEGA which has more than 1 Serial port. Please up-vote the answer if it helped you!

Here it seems to work . http://www.learnerswings.com/2014/03/read-sms-message-by-at-commands-using.html?m=1

The RX/TX pins are on Uno connected to the USB chip. If you connect a device to RX/TX, you should not use Serial Monitor. It sometimes works, but the device receives the data send to Serial Monitor too and can't process them.
Use SoftwareSerial library for connecting the serial device, if you want to have Serial free for printing to Serial Monitor over USB.


text:
Ultrasonic sensor confusion
Here is a code snipet for ultrasonic sensor
digitalWrite(trigpin,HIGH);
delayMicroseconds(10);
digitalWrite(trigpin,LOW);

duration=pulseIn(echopin,HIGH);

Assume trigpin and echopin pins are already defined.
Now according to Arduino reference guide pulseIn funcion:

Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds or 0 if no complete pulse was received within the time out.

So shouldn't I be getting 10 microseconds as my answer, since since initial state of echo pin is low, now when the reflected sound hits receiver, echo pin goes high, the timer gets started and when and when the pulse ends the echo pin goes low again and since pulse sent was of 10 microseconds of length, the ans should be 10, but any ultrasonic program I have seen uses this code to find the duration the ultrasonic wave takes since it gets emitted to the time it gets into the receiver.

What happens is:

You send a pulse of 10 ms with TTL signal. This is the first line in the picture below.
Than you call pulseIn. This waits for the echo pulse.
The echo pulse will become high when reflected. This happens internally in the module. This is the second line.
The echo pulse will stay high depending on the time it took to be echoed back and makes a pin high (echo pin). This is the third line.
Than your pulseIn command returns with the time (of the echo pin length).