text:
arduino nodejs serial data chunked and not in synch
I'm trying to get an arduino sending data to node but with no success.
I'm connecting to an ar-drone 2.0 as in https://gist.github.com/maxogden/4152815
Here is my Arduino code:
    #include <TinyGPS++.h>
    #include <SoftwareSerial.h>
    #include <Wire.h>
    #include "Adafruit_HTU21DF.h"
    /*
      Sketch per creare json contenente
      lat,lon,data,ora,temp, hum
    */
    static const int GPS_RXPin = 16, GPS_TXPin = 10;
    static const uint32_t GPSBaud = 9600;

    Adafruit_HTU21DF htu = Adafruit_HTU21DF();

    // The TinyGPS++ object
    TinyGPSPlus gps;

    // The serial connection to the GPS device
    SoftwareSerial ss(GPS_RXPin, GPS_TXPin);

    //JSON
    const size_t bufferSize = JSON_OBJECT_SIZE(6);
    DynamicJsonBuffer jsonBuffer(bufferSize);
    JsonObject& oData = jsonBuffer.createObject();

    void setup()
    {
      Serial1.begin(9600);
      Serial.begin(9600);
      ss.begin(GPSBaud);
      if (!htu.begin()) {
        Serial1.println("Couldn't find Adafruit_HTU21DF!");
        while (1);
      }
    }

    void loop()
    {
      float lat = gps.location.lat();
      float lon = gps.location.lng();
      float date = gps.date.value();
      float timestamp = gps.time.value();
      float temp = htu.readTemperature();
      float hum = htu.readHumidity();

      Serial1.print(lat);
      Serial1.print(";");
      Serial1.print(lon);
      Serial1.print(";");
      Serial1.print(date);
      Serial1.print(";");
      Serial1.print(timestamp);
      Serial1.print(";");
      Serial1.print(temp);
      Serial1.print(";");
      Serial1.print(hum);
      Serial1.print(";\n");

      //////

      Serial.print(lat);
      Serial.print(";");
      Serial.print(lon);
      Serial.print(";");
      Serial.print(date);
      Serial.print(";");
      Serial.print(timestamp);
      Serial.print(";");
      Serial.print(temp);
      Serial.print(";");
      Serial.print(hum);
      Serial.print(";\n")

      smartDelay(1000);
      if (millis() > 5000 && gps.charsProcessed() < 10)
        Serial1.println(F("No GPS data received: check wiring"));
    }

    // This custom version of delay() ensures that the gps object
    // is being "fed".
    static void smartDelay(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (ss.available())
          gps.encode(ss.read());
      } while (millis() - start < ms);
    }

and this my NodeJS code:
    var serialport = require('node-serialport');
    var WebSocketServer = require('ws').Server;

    var wss = new WebSocketServer({host:'0.0.0.0',port: 9999});
    var sp = new serialport.SerialPort("/dev/ttyO3", {
      parser: serialport.parsers.readline("\n"),
      baud: 9600,
      buffersize: 65536
    });

    wss.on('connection', function(ws) {
      ws.send('connected');
      ws.on('message', function(message) {
        console.log('received: %s', message);
      });
      sp.on('data', function(chunk) {
        var fromArduino = chunk.toString();
        ws.send(fromArduino);
        console.log(fromArduino);
      });
    });

While the CSV comes out nice on Arduino IDE serial monitor, it is all messed up both on ws and node console.

I'm using this version of NodeJS and node-serial: https://github.com/felixge/node-cross-compiler/downloads
and set ttyO3 as in https://gist.github.com/maxogden/4152815
A voltage diveder is set between drone RX and Arduino TX1 to lower signal from 5v to 1.8v.
Thanks for any help!
Lorenzo

UPDATE 2 JUN 2018
I managed to make things a little bettere with the following code:
ARDUINO:
        #include
        #include
        #include "Adafruit_HTU21DF.h"
        /*
          Sketch per creare json contenente
          lat,lon,data,ora,temp, hum
        */
        static const uint32_t GPSBaud = 9600;
    Adafruit_HTU21DF htu = Adafruit_HTU21DF();

    // The TinyGPS++ object
    TinyGPSPlus gps;

    void setup()
    {
      Serial1.begin(9600);
      //  Serial.begin(9600);
      if (!htu.begin()) {
        Serial1.println("Couldn't find Adafruit_HTU21DF!");
        while (1);
      }
    }

    void loop()
    {
      while (Serial1.available()) {
        gps.encode(Serial1.read());
      }
      float lat = gps.location.lat();
      float lon = gps.location.lng();
      int date = gps.date.value();
      float timestamp = gps.time.value();
      float temp = htu.readTemperature();
      float hum = htu.readHumidity();

      Serial1.print(lat);
      Serial1.print(";");
      Serial1.print(lon);
      Serial1.print(";");
      Serial1.print(date);
      Serial1.print(";");
      Serial1.print(timestamp);
      Serial1.print(";");
      Serial1.print(temp);
      Serial1.print(";");
      Serial1.print(hum);
      Serial1.print(";_");
      Serial1.println();
    }

NODE JS:
    var serialport = require('node-serialport');
    var WebSocketServer = require('ws').Server;

    var wss = new WebSocketServer({host:'0.0.0.0',port: 9999});
    var sp = new serialport.SerialPort("/dev/ttyO3", {
      parser: serialport.parsers.readline("_"),
      // parser: serialport.parsers.raw,
      baud: 9600,
      buffersize: 1024
    });
    wss.on('connection', function(ws) {

      sp.on('data', function(chunk) {
        var fromArduino = chunk.toString();
        // console.log(fromArduino);
        ws.send(fromArduino);
        sp.flush();
      });
    });

Now data comes out tidy on both console and ws for most of the times: I guess the problem was the serialport buffersize.
I also removed serial software from Arduino code.

Can't see what's wrong, but a few simplifications could help you nail down the problem: 1. Get rid of SoftwareSerial and use only the hardware serial port: RX from the GPS and TX to the drone. 2. Remove the HTU and JSON code from the Arduino. 3. Remove the WebSockets code from the Node.js. 4. Use parsers.readline("\r\n"), as that's what Serial.println() sends.

since the serial monitor shows correct data, i suspect that your NodeJS code has a bug .... therefore this is not an Arduino question

@lbrutti try getting rid of your parser and directly print every received character from the UART device (/dev/ttyO3) to the console as fast as possible. Maybe a UART buffer is overflowing when it isn't read fast enough. Did you also try Edgar's suggestion?

Hello, i tried removing ws and software serial. Still node output comes out chunked.  I'll try to bypass parsers and let you know. Thanks

@maximilian-gerhardt: i simplified the code by removing software serial and using a smaller buffer. data comes out tidy most of the times: not always but it is accepteable for this early prototyping stage.

Hm at these speeds there should be no problem at reading it out. Could you try lowering the baud rate? (4800, 1200, 300)

Actually, yes, NodeJS serial is expected to give "chunks" your code should put it in a buffer end do the delimiting.

just one miss Sir,
only use instead "baudRate: " not a "baud".
what's a var baud Sir??? Thanks.

  Serial.print(lat);
  Serial.print(";");
  Serial.print(lon);
  Serial.print(";");
  Serial.print(date);
  Serial.print(";");
  Serial.print(timestamp);
  Serial.print(";");
  Serial.print(temp);
  Serial.print(";");
  Serial.print(hum);
  Serial.println(";");

Serial.println will print an \r\n at the end (source). \r is a "carriage return" which will move the curser back to the beginning of the line.
Since you are reading your data with a parser that looks for \n and removes that, you are left with a string that looks like  [csv data..]\r. Once you print that to console verbatim you get the behaviour you are looking at.
Replace Serial.println(";"); by Serial.print(";\n"); (same for Serial1) and see what happens.

hello, unfortunately adding "\n" char at the end of last print didn't help: both console and ws output are messed. Serial Monitor output works well as before.

@lbrutti edit your question to show the updated code, then.


text:
Is there any way to control current precisely with Arduino without using a DC-DC converter?
I have a circuit that consists of a torquer. Its torque is directly proportional to the current in the circuit. I want to precisely control the torque provided by the torquer and hence need to control the current in the circuit. Which is the best technique you would prefer using Arduino?

Depends on what you mean by "control current", what current and what voltage.

@Milliways I have a constant voltage source and wish to control the current in the circuit with Arduino. Can it be done using PWM?

If you want any sensible answer you need the provide detail of what you are trying to control.

@Milliways I have edited the question. I hope it has enough detail :)

There isn't much detail, like part numbers. You may as well ask if the Arduino can be used on the International Space Station. No doubt it could, but you need to provide more detail as to what it is expected to do, and in conjunction with what other circuitry.

Add a current sense resistor. Connect that to an analog pin so you can measure the current. Then change the PWM output value till the current is what you want it to be. Some people use a PID control loop for this.

The Arduino (like other microcontrollers) is a digital device. It doesn't "control current" on its own. It has outputs which can either be off or on. Off is 0V and on is 5V (assuming you are powering it from a 5V supply). The continuous current you can drawn from output pins is 20 mA.
You can use PWM to effectively reduce the power output (for example, a 50% duty cycle would be half on and half off, thus you would have 50% power).
If you drive your torquer from some sort of transistor (eg. a MOSFET) then PWM could conceivably achieve what you are wanting to do. A link to this device would be helpful. Plus, the other circuitry you have in mind.

Yes I have planned to include MOSFET switches. Could you provide details on how to do so? I am a beginner....

source: Stack Exchange

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

authors: Данила Алексеев

sort: votes


text:
can teensy 3.0 or above run fingerprint scanner fps gt-511c1r?
I have an fps gt-511c1r fingerprint sensor module. I want to know whether i can run it using teensy 3.0 or above?
I have tried it successfully using arduino uno.
EDIT: I have uploaded the fps blink sketch on the teensy 3.2 successfully, but the fingerprint scanner is not responding. Here is the code:-
         #include "FPS_GT511C3.h"
         #include "SoftwareSerial.h"
     // Hardware setup - FPS connected to:
     //   digital pin 0(arduino rx, fps tx)
     //   digital pin 1(arduino tx, fps rx)

     FPS_GT511C3 fps(0, 1);

     void setup()
     {
         Serial.begin(9600);
         fps.UseSerialDebug = true;
         fps.Open();
     }

     void loop()
     {
        // FPS Blink LED Test
        fps.SetLED(true);
         delay(1000);
         fps.SetLED(false);
         delay(1000);
     }

connected fps tx to teensy rx(pin 0),
          fps rx to teensy tx(pin 1),
          fps vcc to 3.3v teensy,
          fps gnd to teensy gnd.

Have you tried it on a teensy?

As something with a UART interface there should be very little hardware dependence - presumably the hardware serial library on the Teensy works.  You might avoid or re-work sketches that try to use software serial though, since the Teensy has plenty of hardware serial ports.

Your library looks to be using software serial internally, that is probably not what you want on a Teensy where you have plenty of real UARTs.  Or at least, if you are going to do it that way, make sure you use a version that works on the Teensy ina  way that works on the Teensy.  Some web search research is in order.

Please can u guide me as to how to disable the software serial?

The GT-511C1R is a 5V device. The Teensy 3.0 is a 3.3V device. You will require some level shifting as you would with any 3.3V Arduino connecting to a 5V device.
Besides that, yes, the Teensy 3.0 is more than capable of working with the fingerprint scanner. Will the software work? Most likely, but only trying it will confirm that.

Thank you very much:) i'll definitely try n tell if it works..

What makes you say that "The GT-511C1R is a 5V device" ?  The data sheet says "DC 3.3~6v"

The spark fun site says 5v.

I tried a simple blink code for the fingerprint scanner. It uploaded successfully but there is no response from the scanner:( I uploaded the same code on the arduino uno and powered the scanner with 3.3v and it works. So why isnt it working with teeny?? Even though the sketch is uploaded?

Because you did something wrong, obviously. I have no idea what you did, though, so I don't know what part of it was done wrong.

Can the reason be that teensy is 32 bit for a word whereas the gt-511c1r is a 16 bit for a word?

I don't know. I still can't see what it is you are doing, what your code is, how you have wired it up, nothing.

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


text:
How to blink a series of LED alternately only one at a time
I am very much new to Arduino. I recently bought an adruino uno. i can blink an LED alternately. Such as, 1st blink red, then blink green, then blue like that. once only one LED should blink.
I have provided the code blinking an LED. How to modify this to blink multiple LED one after another.
void setup() {

  pinMode(13, OUTPUT);

}

void loop() {

  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}

Could you please provide some more details? What are you trying to do? What have you tried so far? Are you trying to control multiple LEDs?

Most newbie problems involve more than code. The problem often lies in the wiring. Please give us some information about your wiring.

i have provided code of blinking one LED. now i just want to blink multiple LED one after another. alternately.

Who flagged this a "unclear what you are asking"? It's clear. He wants to blink 3 LEDs in sequence.

yes @NickGammon

You could always copy and paste:
void setup() {

  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);

}

void loop() {

  digitalWrite(11, HIGH);
  delay(1000);
  digitalWrite(11, LOW);
  delay(1000);

  digitalWrite(12, HIGH);
  delay(1000);
  digitalWrite(12, LOW);
  delay(1000);

  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}

A bit better would be to learn about functions:
void setup() {

  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);

}

void blink (const byte which)
  {
  digitalWrite(which, HIGH);
  delay(1000);
  digitalWrite(which, LOW);
  delay(1000);
  }  // end of blink

void loop() {
  blink (11);
  blink (12);
  blink (13);
}

And you could learn about loops:
void setup() {
  for (int i = 11; i <= 13; i++)
    pinMode(i, OUTPUT);
}

void blink (const byte which)
  {
  digitalWrite(which, HIGH);
  delay(1000);
  digitalWrite(which, LOW);
  delay(1000);
  }  // end of blink

void loop() {
  for (int i = 11; i <= 13; i++)
     blink (i);
}

There is a whole world of stuff to learn. Enjoy the process!

thnksssssssss :)

Have you considered connecting another LED and turning one on and the other off sequentially?
void setup() {

  pinMode(13, OUTPUT);
  pinmode(NewLEDPin, OUTPUT);

}

void loop() {
  digitalWrite(NewLEDPin,LOW);
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(NewLEDPin,HIGH);
  digitalWrite(13, LOW);
  delay(1000);
}

i'll try , but what is it "NewLEDPin" ,,, there is no PIn no ..

@user3099225 look, there are two parts to any program, the software and the hardware. The software is in front of you, and the hardware is for you to set up. Connect another led to the board in a similar manner to the way your first led us connected and replace "NewLEDPin" with the pin that the led is connected to


text:
Altering SoftwareSerial to transmit more than 1 byte at a time
I am trying to create a stable communication channel without any mis-synchronization. In the SoftwareSerial library, the write function transmits one byte at a time. The mis-synchronization occurs when the receiver misjudges which bit is the start bit. Why is this a problem? Because the internal delay between the start bit and the first message bit is different from the internal delay between each message bit.
One of the really good suggestions I have heard is to use Manchester encoding on the Arduino. While I am testing out this option, I also wanted advice on altering the software serial library in the following way. If I modify the write function to transmit 128 bytes instead of 1, then this can avoid the problem I explained above, I assume.
Here is how I have altered the write function of SoftwareSerial. I haven't thought of any issues with this approach, but does anyone else see any problems?
Here is the whole altered function. (I changed the parameter, and added 2 new loops - one to invert all the bytes if(inv) and another loop outside the loop that transmits each bit of a byte. I have attached the original function, further below.
size_t SoftwareSerial::write(byte* b)
{
  if (_tx_delay == 0) {
    setWriteError();
    return 0;
  }

// By declaring these as local variables, the compiler will put them
// in registers _before_ disabling interrupts and entering the
// critical timing sections below, which makes it a lot easier to
// verify the cycle timings
volatile uint8_t *reg = _transmitPortRegister;
uint8_t reg_mask = _transmitBitMask;
uint8_t inv_mask = ~_transmitBitMask;
uint8_t oldSREG = SREG;
bool inv = _inverse_logic;
uint16_t delay = _tx_delay;

//Doubtful of this loop ------------------
for(int i = 0; i < 128; i++)
{
  if (inv)
    b[i] = ~(b[i]);
}

cli();  // turn off interrupts for a clean txmit

// Write the start bit
if (inv)
  *reg |= reg_mask;
else
  *reg &= inv_mask;

tunedDelay(delay);
for(int j = 0; j < 128; j++)
{
  // Write each of the 8 bits
  for (long i = 8; i > 0; --i)
  {
    if (b[j] & 1) // choose bit
      *reg |= reg_mask; // send 1
    else
      *reg &= inv_mask; // send 0

    tunedDelay(delay);
    b[j] >>= 1;
  }
}
// restore pin to natural state
if (inv)
  *reg &= inv_mask;
else
  *reg |= reg_mask;

SREG = oldSREG; // turn interrupts back on
tunedDelay(_tx_delay);

return 1;
}

Here is the original function.
size_t SoftwareSerial::write(uint8_t b)
{
if (_tx_delay == 0) {
  setWriteError();
  return 0;
}

// By declaring these as local variables, the compiler will put them
// in registers _before_ disabling interrupts and entering the
// critical timing sections below, which makes it a lot easier to
// verify the cycle timings
volatile uint8_t *reg = _transmitPortRegister;
uint8_t reg_mask = _transmitBitMask;
uint8_t inv_mask = ~_transmitBitMask;
uint8_t oldSREG = SREG;
bool inv = _inverse_logic;
uint16_t delay = _tx_delay;

if (inv)
  b = ~b;

cli();  // turn off interrupts for a clean txmit

// Write the start bit
if (inv)
  *reg |= reg_mask;
else
  *reg &= inv_mask;

tunedDelay(delay);

// Write each of the 8 bits
for (uint8_t i = 8; i > 0; --i)
{
  if (b & 1) // choose bit
    *reg |= reg_mask; // send 1
  else
    *reg &= inv_mask; // send 0

  tunedDelay(delay);
  b >>= 1;
}

// restore pin to natural state
if (inv)
  *reg &= inv_mask;
else
  *reg |= reg_mask;

SREG = oldSREG; // turn interrupts back on
tunedDelay(_tx_delay);

return 1;
}

The serial buffer can only hold 64 bytes at a time, but I am using the following code, courtesy of Nick Gammon to read the data from serial buffer without blocking. So it shouldn't be a problem on the receiving end either, I hope.

You've asked this before - in what way is this question different to your previous one? As I point out in your other question, by trying to send 1024 bits rather than 8 bits, you are substantially reducing the margin for error, if the difference between the sender and receiver clock is at all significant.

The mis-synchronization occurs when the receiver misjudges which bit is the start bit. - that would happen. You would need to allow a really big gap (greater than 1024 bits) to stop this happening. This gap would wipe out any savings by not just sending 8 bits at a time as is normal. I don't see what this technique achieves.

Basically your code has changed the size of the RS-232 packet from 10 bits to 1026 bits. There is nothing "wrong" with that, but it doesn't really solve the problem of a missed start bit - if anything it makes it worse since instead of losing 8 bits you lose 1024 bits.
Synchronisation is best done separately to the transmission of packets, and for that you need your packet to be nice and short.
A packet consists of 10 bits - the first is a LOW and the last is a HIGH; everything else in between is data.  The trick is to provide a forced idle period before sending of at least the amount of time it takes to transfer one packet.  That way if the receiver is mistakenly in a receive loop for whatever reason the 10 (or more) bits worth of HIGH will effectively cause the receiver to finish whatever it is doing and get ready to receive your real byte.
If you have a hugely long packet (1024 + 2 bits) flushing the receiver before transmitting will take a very long time - rather than just one byte's worth of time it will be your entire packet's transmit time.
On top of that you then have the problem of byte order and data integrity checking.  Just sending two bytes (or 128 bytes) is not reliable. You need to wrap those bytes in a protocol including a start-of-packet indicator (0x55 0xAA is common, as is the special ASCII character 0x01: SOH), packet or payload length, and checksums.  Options for things like sequence numbers, acknowledgements, packet retransmission, etc can also be built in to increase the reliability of the protocol.
Rather than trying to reinvent the wheel by changing the underlying data layer transmission you should learn the OSI 7 layer model and implement your protocol at a higher level than the data layer.

Just a quick clarification, isn't the start bit a one, which is a high?

The start bit is always a zero. See http://www.gammon.com.au/forum/?id=10894. The "idle state" is continuous 1 bits.

Coincidentally, you should learn the OSI 7 layer model is what I recommended, too.

So far you have asked a lot of questions about your project which uses SoftwareSerial to send a lot of bits:

How to transmit more than 1 byte continually?
Basic Serial Transmission Protocol
Synchronization and Implementing hamming code on Software Serial
Encoding clock signal into linear block codes
How to fix baud rate when hardware capacity has a low limit?
Unable to tell if error is from receiving or transmitting end
Read function in Software Serial

And now we have another one (this question).
I think you are flogging a dead horse with this. For one thing, what are you trying to achieve, that can't be achieved by just sending the bytes "normally" as 8-bit bytes? The only thing I can think of is a slight speed increase. By trying to make a 1024-bit packet, you are saving some start and stop bits in the middle, that's all.
In some of your other questions you mention 9600 baud, so let's run with that. At 9600 baud one bit is 1/9600 of a second, that is 104.17 µs.
To transmit 1024 bits "normally" you would need 128 bytes, each of which needs a start and stop bit, so the total is 128 * 10 * 104.17 µs = 133.338 ms.
To use your system you need 1024 bits plus one start and stop bit, so that is 1026 * 104.17 µs = 106.878 ms.
So far you have only saved 26.46 ms.
You could save a lot more by simply doubling the baud rate. Or quadrupling it. However SoftwareSerial is less reliable at higher baud rates. Why not use HardwareSerial?
Your next problem is that SoftwareSerial turns interrupts off during reception of one byte, so that it gets the timing right. For an 8-bit byte this means they are off for 10 * 104.17 µs = 1.0417 ms. That's about the limit for turning interrupts off if you want the internal timer to work, the one which gives you millis and micros. If you turn them off for 128 times as long, you can say "goodbye" to knowing how much time has elapsed.
As I mentioned in a comment, too, since serial comms relies on external clocks (that is, both ends have to get the clocking right) you can only afford around a ±2% error in the receiving clock to ensure that we are sampling at the correct place (see the datasheet) for an 8-bit byte. The error tolerance will drop to 1/128th of that if you try to send 128 bytes in a single stream. The crystal/resonator in the Arduino just won't be that good.
Finally, to avoid false detection of the start bit (which you have asked about elsewhere) you need a much longer gap between packets, to ensure that we get the correct start bit. Effectively you need a one-byte length (ie. the incoming data is continually HIGH) for 8-bit bytes. For 1024-bit packets you will need to introduce a gap of 1024 * 104.17 µs = 106.670 ms between packets. This required gap totally wipes out any saving by not sending those extra start and stop bits.


text:
Alternative to delay function
I am trying to make a workaround for the delay function. I am trying to use the function in the Analog Write Mega example, by replacing delay with the function i made. However, whenever i use my function instead of delay i get incorrect led behaviour.
Here is the link to the example:
https://www.arduino.cc/en/Tutorial/AnalogWriteMega
Here is my code:
int currmillis = 0; //used in my function to find the current millis()
int prevmillis = 0; //used to hold previous value of currmillis
int boolval = 0;    //used to control whether to write the brightness value to the led or not
int time = 0;     //used in the delay function, difference between currmillis and prevmillis

int timeloop(int); //the function i wrote, it is at the bottom of the code

void setup() {
  Serial.begin(9600);
  for ( int i = 2; i <= 13; i++)
  {
        pinMode(i,OUTPUT);
  }
}//Setting the pins to output and allowing serial communication.

void loop (){

  for ( int thisPin = 2; thisPin <= 13; thisPin++ ) //to move from one led to the next
  {

    for ( int brightness = 0 ; brightness <= 255; brightness++) //change the brightness of the led
    {

      boolval = timeloop(2); //the delay function returns the time passed, if the time is greater than or equal to 2, the analogWrite will write the brightness to the led

      if (boolval >= 2){
            analogWrite(thisPin, brightness);
      }// if 2 ms pass, the led brightness will increase from 0 to 255 and then decrease in the following loop from 255 to 0, Once it reaches 0, the main loop moves to the next led.

    }

    for ( int brightness = 255 ; brightness >= 0 ; brightness--)
    {
      boolval = timeloop(2);

      if (boolval >= 2){
            analogWrite(thisPin, brightness);
      }
    }
          timeloop(100); // a delay of 100 ms using the function
  }
}

int timeloop (int interval){ // the delay function

  do{
    prevmillis = currmillis; //hold previous value
    currmillis = millis(); //find current value
    time = (currmillis-prevmillis);
  }while(time < interval);

  return time;
}

Thank you

Your function is a pure delay. Why do you want to rewrite it? What different behaviour do you want?

// You don't need to return anything since it's just a delay
// also I changed the parameters to long ints because millis()
// returns a long int
void timeLoop (long int startMillis, long int interval){ // the delay function

    // this loops until 2 milliseconds has passed since the function began
    while(millis() - startMillis < interval){}
}

// Your call for a 2 millisecond delay would be
timeLoop(millis(), 2);

Also the leds may be acting weird because this schematic is wrong. As you can see one of the led's anode isn't connected to ground. It's circled in red.

If you really want it to return something you could use this:
long int timeLoop (long int startMillis, long int interval){ // the delay function

    while(millis() - startMillis < interval){}
    return millis() - startMillis;
}

But it really isn't needed.

thank you - seems super hard to find functional functions on arduino sites

Depending on what you want the alternative function to do, there are a megaton of timer libraries at the Arduino playground. One of them is likely to provide what you need.

What's the point? Why rewrite delay()?
Anyway:
int timeloop (int interval){ // the delay function

  do{
    prevmillis = currmillis; //hold previous value
    currmillis = millis(); //find current value
    time = (currmillis-prevmillis);
  }while(time < interval);

  return time;
}

In every iteration of that loop you are updating prevmillis. So you will never reach the wanted delay interval.
Apart from the fact that you may as well use the inbuilt delay rather than writing your own, and getting it wrong.

I am trying to make a workaround for the delay function

Why?
The XY Problem

The "Why" part interested me here, because I'm in the process of changing my delay(1000) to a millis() interval. Why? because I want a more accurate timer for sending data via serial. I need the processing time to be deducted from the one second delay, so the interval between loops is as close to 1 second as possible. That's fair and achievable, right?

"W": Because I think that is more sensible than sending and displaying data at an arbitrary rate, as my application involved scheduling to real-world time. "V": So that a user can schedule an event as part of the automation program! "U": Because...    ..."F-22": Because I wasn't breast fed!... ..."M-6.832810^11": Because the big bang singularity occurred! "L-6.832810^11": Unknown.

What? Did the cat get loose on the keyboard?

lol. Do you get it? It's my extension of "The XY Problem"!


text:
Sending Something to Serial and Writing it Returns a Correlated but Strange Number
I have an indescribable bug where read and write commands give back an array of numbers that are the digits of the input number except +48. Kinda hard to explain. Basically if I type 0 into this code:
    void setup(){
      Serial.begin(9600); //Begin serial connection
    }
    void loop(){
      if(Serial.available()){ //If serial available...
        double ser = Serial.read(); //Read serial value and write it to 'ser'
        Serial.println(ser); //Print 'ser'
      }
    }

I receive 48. 1 means 49, 2 means 50, 3 means 51... And then two digit numbers, which are the same except for each digit. 10 returns 49 48, 33 returns 51 51, 22 returns 50 50.

Serial.read returns a character. The character '0' is 48 in decimal. So this is doing what you expect (or what I expect, anyway). I suggest not using double there, eg.
    char ser = Serial.read(); //Read serial value and write it to 'ser'

Thanks, but I have to output the value I get to a servo, which needs an int and it still separates the different characters into an array. Do you mind telling me a way to convert it into a full int?

which needs an int and it still separates the different characters into an array - I don't understand that. What array?

When transmitted textually, multi-digital value will indeed appear as something like a character array of the ASCII encoding of its digits.

Often we send 4 characters like "1234" over the serial link and want to store them in a single integer like "int position = 1234". One way to do it is to store the characters into a temporary buffer, and then use "atoi()" or "atol()". Another way is convert digits to an integer on the fly. Yet another way is to use Serial.parseInt().


text:
Arduino IDE installation Problems
When installing the IDE there are many "Unable to open *.DLL", errors. I check "ignore errors" and the IDE installed. Now when selecting the correct port and  board the blink sketch is uploaded and several ATK 500 errors result. I have uninstalled and reinstalled the IDE several time, with repeated results.

You should check to make sure that your Java installation is up to date. It would also be best to make sure that you're bit types between the Java environment and the Arduino IDE are the same(32bit with 32bit, 64bit with 64bit). If this does not work, you should post your actual errors so we can help more :)

I updated my Java and that solved the problem. I appreciate your help Brad.


text:
Refine Colorview Code
How would I refine this to only recognize red and green? I don't need the full functionality of this code, just the ability to distinguish between red and green, and output that respectively.
I also would like to eliminate the bleed over; meaning, the green led stays on slightly when I flood the Adafruit with red light and vice versa. I am not really familiar with the output of the Adafruit, but it seems this could be an analog "question and answer" situation; it's either green or red or nothing.
#include <Wire.h>
#include "Adafruit_TCS34725.h"

#ifndef _TCS34725_H_
#define _TCS34725_H_

#if ARDUINO >= 100
 #include <Arduino.h>
#else
 #include <WProgram.h>
#endif

#include <Wire.h>

#define TCS34725_ADDRESS          (0x29)

#define TCS34725_COMMAND_BIT      (0x80)

#define TCS34725_ENABLE           (0x00)
#define TCS34725_ENABLE_AIEN      (0x10)    /* RGBC Interrupt Enable */
#define TCS34725_ENABLE_WEN       (0x08)    /* Wait enable - Writing 1 activates the wait timer */
#define TCS34725_ENABLE_AEN       (0x02)    /* RGBC Enable - Writing 1 actives the ADC, 0 disables it */
#define TCS34725_ENABLE_PON       (0x01)    /* Power on - Writing 1 activates the internal oscillator, 0 disables it */
#define TCS34725_ATIME            (0x01)    /* Integration time */
#define TCS34725_WTIME            (0x03)    /* Wait time (if TCS34725_ENABLE_WEN is asserted) */
#define TCS34725_WTIME_2_4MS      (0xFF)    /* WLONG0 = 2.4ms   WLONG1 = 0.029s */
#define TCS34725_WTIME_204MS      (0xAB)    /* WLONG0 = 204ms   WLONG1 = 2.45s  */
#define TCS34725_WTIME_614MS      (0x00)    /* WLONG0 = 614ms   WLONG1 = 7.4s   */
#define TCS34725_AILTL            (0x04)    /* Clear channel lower interrupt threshold */
#define TCS34725_AILTH            (0x05)
#define TCS34725_AIHTL            (0x06)    /* Clear channel upper interrupt threshold */
#define TCS34725_AIHTH            (0x07)
#define TCS34725_PERS             (0x0C)    /* Persistence register - basic SW filtering mechanism for interrupts */
#define TCS34725_PERS_NONE        (0b0000)  /* Every RGBC cycle generates an interrupt                                */
#define TCS34725_PERS_1_CYCLE     (0b0001)  /* 1 clean channel value outside threshold range generates an interrupt   */
#define TCS34725_PERS_2_CYCLE     (0b0010)  /* 2 clean channel values outside threshold range generates an interrupt  */
#define TCS34725_PERS_3_CYCLE     (0b0011)  /* 3 clean channel values outside threshold range generates an interrupt  */
#define TCS34725_PERS_5_CYCLE     (0b0100)  /* 5 clean channel values outside threshold range generates an interrupt  */
#define TCS34725_PERS_10_CYCLE    (0b0101)  /* 10 clean channel values outside threshold range generates an interrupt */
#define TCS34725_PERS_15_CYCLE    (0b0110)  /* 15 clean channel values outside threshold range generates an interrupt */
#define TCS34725_PERS_20_CYCLE    (0b0111)  /* 20 clean channel values outside threshold range generates an interrupt */
#define TCS34725_PERS_25_CYCLE    (0b1000)  /* 25 clean channel values outside threshold range generates an interrupt */
#define TCS34725_PERS_30_CYCLE    (0b1001)  /* 30 clean channel values outside threshold range generates an interrupt */
#define TCS34725_PERS_35_CYCLE    (0b1010)  /* 35 clean channel values outside threshold range generates an interrupt */
#define TCS34725_PERS_40_CYCLE    (0b1011)  /* 40 clean channel values outside threshold range generates an interrupt */
#define TCS34725_PERS_45_CYCLE    (0b1100)  /* 45 clean channel values outside threshold range generates an interrupt */
#define TCS34725_PERS_50_CYCLE    (0b1101)  /* 50 clean channel values outside threshold range generates an interrupt */
#define TCS34725_PERS_55_CYCLE    (0b1110)  /* 55 clean channel values outside threshold range generates an interrupt */
#define TCS34725_PERS_60_CYCLE    (0b1111)  /* 60 clean channel values outside threshold range generates an interrupt */
#define TCS34725_CONFIG           (0x0D)
#define TCS34725_CONFIG_WLONG     (0x02)    /* Choose between short and long (12x) wait times via TCS34725_WTIME */
#define TCS34725_CONTROL          (0x0F)    /* Set the gain level for the sensor */
#define TCS34725_ID               (0x12)    /* 0x44 = TCS34721/TCS34725, 0x4D = TCS34723/TCS34727 */
#define TCS34725_STATUS           (0x13)
#define TCS34725_STATUS_AINT      (0x10)    /* RGBC Clean channel interrupt */
#define TCS34725_STATUS_AVALID    (0x01)    /* Indicates that the RGBC channels have completed an integration cycle */
#define TCS34725_CDATAL           (0x14)    /* Clear channel data */
#define TCS34725_CDATAH           (0x15)
#define TCS34725_RDATAL           (0x16)    /* Red channel data */
#define TCS34725_RDATAH           (0x17)
#define TCS34725_GDATAL           (0x18)    /* Green channel data */
#define TCS34725_GDATAH           (0x19)
#define TCS34725_BDATAL           (0x1A)    /* Blue channel data */
#define TCS34725_BDATAH           (0x1B)

typedef enum
{
  TCS34725_INTEGRATIONTIME_2_4MS  = 0xFF,   /**<  2.4ms - 1 cycle    - Max Count: 1024  */
  TCS34725_INTEGRATIONTIME_24MS   = 0xF6,   /**<  24ms  - 10 cycles  - Max Count: 10240 */
  TCS34725_INTEGRATIONTIME_50MS   = 0xEB,   /**<  50ms  - 20 cycles  - Max Count: 20480 */
  TCS34725_INTEGRATIONTIME_101MS  = 0xD5,   /**<  101ms - 42 cycles  - Max Count: 43008 */
  TCS34725_INTEGRATIONTIME_154MS  = 0xC0,   /**<  154ms - 64 cycles  - Max Count: 65535 */
  TCS34725_INTEGRATIONTIME_700MS  = 0x00    /**<  700ms - 256 cycles - Max Count: 65535 */
}
tcs34725IntegrationTime_t;

typedef enum
{
  TCS34725_GAIN_1X                = 0x00,   /**<  No gain  */
  TCS34725_GAIN_4X                = 0x01,   /**<  4x gain  */
  TCS34725_GAIN_16X               = 0x02,   /**<  16x gain */
  TCS34725_GAIN_60X               = 0x03    /**<  60x gain */
}
tcs34725Gain_t;

class Adafruit_TCS34725 {
 public:
  Adafruit_TCS34725(tcs34725IntegrationTime_t = TCS34725_INTEGRATIONTIME_2_4MS, tcs34725Gain_t = TCS34725_GAIN_1X);

  boolean  begin(void);
  void     setIntegrationTime(tcs34725IntegrationTime_t it);
  void     setGain(tcs34725Gain_t gain);
  void     getRawData(uint16_t *r, uint16_t *g, uint16_t *b, uint16_t *c);
  uint16_t calculateColorTemperature(uint16_t r, uint16_t g, uint16_t b);
  uint16_t calculateLux(uint16_t r, uint16_t g, uint16_t b);
  void     write8 (uint8_t reg, uint32_t value);
  uint8_t  read8 (uint8_t reg);
  uint16_t read16 (uint8_t reg);
  void setInterrupt(boolean flag);
  void clearInterrupt(void);
  void setIntLimits(uint16_t l, uint16_t h);
  void     enable(void);

 private:
  boolean _tcs34725Initialised;
  tcs34725Gain_t _tcs34725Gain;
  tcs34725IntegrationTime_t _tcs34725IntegrationTime;

  void     disable(void);
};

#endif

// Pick analog outputs, for the UNO these three work well
// use ~560  ohm resistor between Red & Blue, ~1K for green (its brighter)
#define redpin 3
#define greenpin 5
#define bluepin 6
// for a common anode LED, connect the common pin to +5V
// for common cathode, connect the common to ground

// set to false if using a common cathode LED
#define commonAnode true

// our RGB -> eye-recognized gamma color
byte gammatable[256];

Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_4X);

void setup() {
  Serial.begin(9600);
  Serial.println("Color View Test!");

  if (tcs.begin()) {
    Serial.println("Found sensor");
  } else {
    Serial.println("No TCS34725 found ... check your connections");
    while (1); // halt!
  }

  // use these three pins to drive an LED
  pinMode(redpin, OUTPUT);
  pinMode(greenpin, OUTPUT);
  pinMode(bluepin, OUTPUT);

  // thanks PhilB for this gamma table!
  // it helps convert RGB colors to what humans see
  for (int i=0; i<256; i++) {
    float x = i;
    x /= 255;
    x = pow(x, 2.5);
    x *= 255;

    if (commonAnode) {
      gammatable[i] = 255 - x;
    } else {
      gammatable[i] = x;
    }
    //Serial.println(gammatable[i]);
  }
}

void loop() {
  uint16_t clear, red, green, blue;

  tcs.setInterrupt(false);      // turn on LED

  delay(60);  // takes 50ms to read

  tcs.getRawData(&red, &green, &blue, &clear);

  tcs.setInterrupt(true);  // turn off LED

  Serial.print("C:\t"); Serial.print(clear);
  Serial.print("\tR:\t"); Serial.print(red);
  Serial.print("\tG:\t"); Serial.print(green);
  Serial.print("\tB:\t"); Serial.print(blue);

  // Figure out some basic hex code for visualization
  uint32_t sum = clear;
  float r, g, b;
  r = red; r /= sum;
  g = green; g /= sum;
  b = blue; b /= sum;
  r *= 256; g *= 256; b *= 256;
  Serial.print("\t");
  Serial.print((int)r, HEX); Serial.print((int)g, HEX); Serial.print((int)b, HEX);
  Serial.println();

  //Serial.print((int)r ); Serial.print(" "); Serial.print((int)g);Serial.print(" ");  Serial.println((int)b );

  analogWrite(redpin, gammatable[(int)r]);
  analogWrite(greenpin, gammatable[(int)g]);
  analogWrite(bluepin, gammatable[(int)b]);


text:
Trying to understand compilation error message
C:\Users\Field\Documents\Arduino\Adafruit_TCS34725-master\examples\tcs34725autorange\tcs34725autorange.ino:2:31: fatal error: Adafruit_TCS34725.h: No such file or directory

 #include "Adafruit_TCS34725.h"

                               ^

compilation terminated.

exit status 1
Error compiling.

Did you try installing the library?

I got it, I goofed on installing the library.

You are trying to use a library, but it is either not installed, or is installed in the wrong location. A library, in this context, is code that supports a sensor or some other hardware or that accomplishes a task. We call them libraries because we can share and reuse them – like borrowing a book from a library.
It looks like you're trying to get the Adafruit TCS34725 color sensor going. The official source of the library is in the Adafruit's GitHub repository for the TCS34725 and there is a link at the bottom of the README for how to install a library. I'll bet that will get you back on track.

I got it, messed up on installing the library


text:
Converting data between baud rates
This isn't strictly limited to Arduino but I spend a lot of time with serial devices on my Arduino and I'm sure that others do as well:
Here goes..
Let's say a device sends three characters [ABC] via serial at 9600 8N1.
And let's also say the device receiving the data only knows that it's serial stream and 8N1 but does not know the baud.
The receiving device would need to take a guess at the baud and so probably get it wrong. It would therefore receive weird characters.
Is there anyway/anything around that a user could paste the strange characters into that would reverse engineer (from the bit stream) to give the correct baud and hence correct ascii characters [ABC]?

I am not aware of anything like that, no.  The problem is what you are seeing as characters are a complete corruption of the data. Only some part of it may have been interpreted as a valid bit sequence, and even then you can't know what bit it was.
However, there is one magic character in UART communication: U
What is special about that character is its binary pattern.  It is ASCII character 85, which in HEX is 0x55, or binary it's 0b01010101.  Add to that the start and stop bits, and invert it for the UART logic (1 = LOW, 0 = HIGH) and the signal that gets sent out of the UART looks like:
____start_____     _____     _____     _____     _____
    |   |  0  | 1 |  0  | 1 |  0  | 1 |  0  | 1 | stop
    -----     -----     -----     -----     -----

And yes, that's a pretty good square wave.  The frequency of that square wave will be exactly half the baud rate - so a frequency of 4800Hz will be a baud rate of 9600 baud.
This effect is cleverly used for a system called Automatic baud rate detection whereby a receiver waits for a U character to determine the baud rate to use.  Most modern microcontrollers have this facility available.
If you can't get the frequency of a block of U characters you will have to examine the waveform with an oscilloscope.  It should be possible to identify the individual characters in the data stream as distinct blocks in the waveform.  From that you can then work out the width of one symbol and thus the baud rate.  It's best to use a DSO for this since you can then capture a short burst and use the markers to measure the time between different points in the waveform.  A logic analyser will also do the job quite well, and will most likely be able to decode the waveform and calculate the baud rate for you.
If you have neither of those it would be possible to program an Arduino to capture the time between transitions of an incoming signal and allow you to plot them in Excel to give you a waveform you can examine to determine the baud.
Another option is just to keep trying different baud rates (there's relatively few "standard" baud rates) until you see the right text coming in.

Thanks.  Following your Autobaud link down to https://en.wikipedia.org/wiki/Synchronous_Idle I found the ASCII SYN byte 0b00010110 which helps to align the frames.

There are a few papers on auto baudrate detect that might be of interest; https://www.silabs.com/Support%20Documents/TechnicalDocs/AN635.pdf, http://www.ti.com/lit/an/slaa215/slaa215.pdf, https://www.pjrc.com/tech/8051/autobaud.html, http://www.google.com/patents/US6072827

The UART logic is not inverted: 0 is LOW. But bits are transmitted least significant first.

My logic analyser has a "guess baud rate" feature, which usually is fairly accurate. If you analyse an incoming bit stream you can probably have a reasonably good guess. For example the shortest transition means the baud rate cannot be slower than that. For example, at 9600 baud sooner or later you will get a transition in 104 µs (ie. 1/9600). Thus if you see that, the baud rate could not be 4800 baud.
Also, in general, there will be a gap between "packets", so in your case after the "ABC" there would be a longer gap (of all 1s). You would assume then that the active time represents an integral number of bytes (eg. 3 bytes, 8 bytes, but not 1.5 bytes).
Another thing is that baud rates are usually multiples of a power of 2 times 300 (ie. 300, 600, 1200, 2400, 4800). So this gives you a small range of possible baud rates to test. You could test (say for 9600) and see if you get reasonable results. A "reasonable result" would be a stop bit appearing 10 bits after a start bit.
See my post: How does serial communications work on the Arduino?

In the days of dumb terminals and time sharing systems, setting the baud rate was accomplished by the terminal sending a pre-determined series of characters with gaps between them and the host changing its baud rate and looking for the expected data. It is best to start at a high baud rate and drop the rate between tries.
For example the terminal user would hit Enter repeadedly and the host would try decreasing baud rates until it saw the Carriage Return character. When it saw the CR, it would respond with "Login Please" and you would know you were good to go.

Try measuring pulse width and match shortest pulse against pre-defined widths corresponding to available baudrates. This way you can detect baudrate by analysing random binary stream.
Signal glitches, such as very short spikes, will be filtered out, as they will never match the list of baudrates.
Repeat the measurement few times to raise accuracy and choose the most probable value from all guessed values.


text:
GSM and Bluetooth modules on 1 Arduino Uno board
I couldn't find anything on this topic.
Task: to connect sensors to Arduino board via Bluetooth module, process the received data and then send the data to server via GSM module.
Question: Is it possible to connect both of these modules to 1 Arduino board? If I'm not wrong, Arduino Uno has only one pair of Rx Tx pins, while for these two modules each has its own pairs on Rx Tx pins.
I need to know this before ordering them. So, please help

It sounds to me that a Raspberry Pi with a BT and GSM dongle would be better/easier/cheaper in this situation.

Or a cheap cellphone with a custom app.

Take a look at the SoftwareSerial library which allows other pins to be used for Serial at speeds <= 57600
https://www.arduino.cc/en/Reference/SoftwareSerial

This is still problematic, as typically only one instance is supported, so the hardware serial must be repurposed from debug/uploading, which creates a lot of development headaches.  Essentially a classic Arduino is not the right choice for this.  Even something like a Leonardo would be better.

Hi @Chris, a board such as a mega2560 would better because it has a number of extra hardware serial ports but the question was for the Uno. Marat confirmed he has the one pair of tx/rx working so second port via SoftwareSerial will work well.

It may work, but only problematically - that single hardware serial is usually reserved for communication between the ATmega and development system.  Using it for communicating with something else means losing that, and having to take steps to de-conflict it, ie, providing a way to disconnect the peripheral during programming or using a different programming method such as ISP than the bootloader which is typically used with an Uno.

There are plenty of solutions I know of on the main hardware serial that don't affect upload. I agree it's a bit cumbersome having to disconnect rx/tx during upload but it's been the default workflow for many users for a long time. Plus software serial tx (1 pin) for debug is okay alongside other software serial. Quite often the bluetooth and gsm code can perform tasks on demand and at separate times allowing them both to use SoftwareSerial leaving the main port free. It's only a problem if the two soft connections are streaming data over the tx at the same time. So does depend on the usage.


text:
Ensuring specific frequency at specific time?
I, at the moment am trying to come up with a simple way where I can program an Arduino to provide a step signal with a given frequency, at a specific time.
The frequency has to be ramped up, and within a time duration of 10 seconds shall the frequency go from 0 Hz to 48000 Hz.
How do I ensure both the specific time of when the frequency occurs, and the specific frequency of the step signal?
Signal has to be used to driver a stepper motor.
Edit: Code current:
So i currently wrote this piece of code:
int timestep = 1;
while(1)
{
  unsigned long startTime = millis()
  while(startTime != 500)
  {
    digitalWrite(step_pin,LOW);
    delayMicroseconds(208/timestep);
    digitalWrite(step_pin,HIGH);
    delayMicroseconds(208/timestep);
  }

  timestep++;
}

For each 0.5s should the frequency be doubled..  would this work?
Edit 2.0:
I made an new implementation using @EdgarBonet 's answer, and with the help of Timer1 library that arduino provide (I guess?).
.h file
#ifndef stepper_motor_h
#define stepper_motor_h

#include "Arduino.h"
#include <TimerOne.h>

#define step_pin  13
#define dir_pin   12
#define en_pin    11
#define max_step  200

 class stepper_motor
{
  public:
    stepper_motor();
    void step_pwm();
    static void callback();
    TimerOne timer1;
  private:
    //uint32_t period;
    bool alive_bool;
    //int step_count;
    bool position_bool;
};

#endif

.cpp file
#include "stepper_motor.h"

int step_count = 0;
uint32_t period = 40825UL << 16; // 20412,5 us fixed point arithmetic time = 0

stepper_motor::stepper_motor()
{
  //pinMode(BUILTIN_LED,OUTPUT);
  pinMode(step_pin, OUTPUT);
  pinMode(dir_pin, OUTPUT);
  pinMode(en_pin, OUTPUT);
  alive_bool = true;
  position_bool = false;
  step_count = 0;

}

static void stepper_motor::callback()
{
  if (step_count < 240)
  {
    uint32_t new_period = sqrt(2 * step_count / 4.8);
    period -= new_period;
    step_count++;
  }
  else
  {
    return;
  }
}

void stepper_motor::step_pwm()
{

  digitalWrite(en_pin, HIGH);

  delay(0.005);

  digitalWrite(dir_pin, HIGH);
  //LOW  - Move towards the sensor
  //HIGH -  Move away from the sensor

  delay(0.005);

  timer1.initialize(period);
  timer1.attachInterrupt(callback);
  timer1.pwm(step_pin, 512);

}

By “step signal” you mean a square signal? I would use Timer 1 for that, but this is more AVR programming than Arduino programming. Do you need the ramp to be linear?

Sounds like you need to model your ramping function's acceleration such that you can calculate exactly how long in advance you need to start it in order to hit the target rate at exactly the target time.

yes to the above questions..

At 48 kHz, you have to toggle the output every 10.4 µs. If you try to do this in software, you will get an awful lot of jitter, unless you use hand-tuned assembly with interrupts disabled. On this time scale, a hardware timer is the simplest way to get consistent timings.

Generating a linear frequency ramp with accurate timings is not an easy
task. I am providing here only a partial answer, where I first go
through the math of the problem, then give some ideas for the
implementation.
The math
We are dealing with a frequency-modulated signal, with the frequency
ramping linearly from f = 0 at t = 0 up to a
maximum f = fM at
t = tM. Specifically, we have
fM = 48 kHz and
tM = 10 s.
Then, the instantaneous frequency is
f(t) = a t
where a = fM/tM = 4.8
kHz/s is the “acceleration” of the pulsed signal.
Let's define the “integrated frequency” as
n(t) = ∫ f(t) dt = a t²/2
This quantity can be interpreted as the number of cycles completed at
time t, except that it is a continuous variable. The first cycle
starts when n = 0 and ends when n = 1, the next
cycle starts when n = 1 and ends when n = 2, and
so on. The output signal would be high when the fractional part of n
is between 0.25 and 0.75 (or maybe between 0 and 0.5, depending on your
choice of initial phase).
From here, we can calculate at what time each cycle should start:
t(n) = √(2 n/a)
and, by successive differences, the length of each cycle:
n       0     1       2       3      ... 239,998    239,999    240,000
t       0     20,412  28,868  35,355 ... 9,999,958  9,999,979  10,000,000
length   20,412   8,455   6,488      ...        20.833     20.833
diff          -11,957 -1,967  -1,018 ...            -0.000043
approx        +81,650 -1,408  -913   ...            -0.000043

In the table above, all times are in microseconds. The lines are:

t: time
length: length of one cycle
diff: difference between lengths of successive cycles
approx: approximated formula for that difference

The columns are staggered because each cycles spans the duration between
two successive values of t, and duration differences are computed
between successive cycles. The approximated formula is based on the
Taylor expansion:
T(n+1) − T(n) ≈ dT/dn + 1/2 d²T/dn² = −aT³(1 − 3/2 aT²)
where T = 1/f, the instantaneous period, approximates the
length of one cycle. The approximation is not good for the very first
cycles, but it converges pretty fast to the correct value.
Implementation
I did not write an implementation, so I am giving here only some ideas
on how to do it.
I would use Timer 1 of the Arduino Uno, in one of the modes that allows
frequency-modulation, i.e. a PWM mode where the counter TOP is set by a
register (mode 8, 9, 10, 11, 14 or 15). I would set the prescaler to 8
in order to allow for the maximum required period length. The period
resolution would then be:

8 CPU cycles = 0.5 µs in modes 14 or 15 (fast PWM)
16 CPU cyels = 1 µs in the other modes

It could be noted that single-cycle resolution is possible with the
prescaler set to 1, but the first 5 cycles are too long for this
setting. Maybe the prescaler could be changed after the fifth cycle, but
it would be tricky to do so without any glitch.
The timer overflow interrupt would fire at the end of each cycle, and
it's ISR (namely TIMER1_OVF_vect) would be responsible for updating
the timer period in order to make the next cycle shorter than the one
just elapsed. It would do something like
period -= delta(period);

The period should be computed with 32-bit arithmetic, because the
changes get tiny by the end of the ramp. Only the 16 most
significant bits of the computed period would actually be written to the
timer register. The delta() function should be inlined and fast. I may
try the approximation from the previous section implemented in
fixed-point. Or maybe just a table lookup using only the most
significant bits of the period as an index, with the table in PROGMEM.
For details on how to actually program the timer, see
the datasheet of the ATmega328P, section 16.

Update: The following algorithm seems to work well. At least in
simulation, I did not put it inside an ISR. It assumes fast PWM, i.e. a
0.5 µs timer resolution. It remembers the current value of delta
and divides it by 2 each time the period falls below some threshold. The
computed f(t) is almost as smooth as you can expect given the
limited resolution of the timer.
uint32_t period = 40825UL << 16;  // 1st cycle is 20412.5 us
void update_period()  // should be in ISR(TIMER1_OVF_vect)
{
    static const uint16_t thresholds[] = {
            17633, 13309, 10229, 7954, 6230, 4905, 3873, 3063,
            2426, 1923, 1525, 1211, 960, 762, 605, 480, 381,
            302, 240, 190, 151, 120, 95, 76, 60, 48};
    static uint16_t threshold = 29000;
    static uint8_t index = 0;
    static uint32_t delta = 6UL << 27;

    uint16_t period_h = period >> 16;
    if (period_h <= 42) return;  // final frequency achieved
    if (period_h < threshold) {
        threshold = thresholds[index++];
        delta >>= 1;
    }
    period -= delta;
    // set the timer period register to (period >> 16) - 1.
}

this might be me who is being stupid.. I have some question regarding the math you introduce.
f(t) => the linear increase of the frequency i am interested in. -> Makes sense..
N(t) => the integrated frequency => provides the number of cycles completed at time t. number of cycles pr. unit time => the frequency.
What do i gain from n(t) which i do not gain from f(t)?

@CarltonBanks: n(t) is a number of cycles, it's not a number of cycles per unit time. It's most useful for computing the length of the very first cycle (≈ 20.4 ms). From the frequency alone, it's hard to tell: what should be the initial period given that the initial frequency is zero?

So you basically use n(t) to know how many cycles should be completed at the given time, such that you can adjust the period to allign with n(t)?

you actually using n(t) to kickstart the system, as you say, that having frequency = 0 would not create a computable period.

how do you get the t(n) expression ?

@CarltonBanks: Given that n = at²/2, I just extract t from that expression: t² = 2n/a.

Ok.. I think i get the math..
About the implementation.
https://code.google.com/archive/p/arduino-timerone/downloads
has some libraries for interfacing with the timer1.
It initialises the timer1 in mode 8.
The library kinda of does use of the timer1 pretty easy, i only have to give the period and that it.
The big question is how should i use the timer1, to know how much time has gone, or how many cycles has been performed.

I guess unsigned long TimerOne::read() could be used to determine how much time has passed.

Where do implement the math you explain..
What are the functions period and delay, comparable to the math you described above.

@CarltonBanks: Interesting library. You could try to update the timer period in a function registered with TimerOne::attachInterrupt(). TimerOne::setPeriod() can change the prescaler though, which could make a small glitch, although it may not be very significant. TimerOne::read() returns the time elapsed within the current cycle: unlikely to be useful to you. I could not understand your last question.

My last question was regarding the implementation of the math in the software...
As it seem to me, are you suggesting that create a precomputed table and use the timer, to step through the table given a specific time interval has passed, specified by the table.

Let us continue this discussion in chat.

Hi @EdgarBonet ..
Would it be possible to get your comment on my implementation of your implementation..  I will add to post above.

As mentioned in comments and other answers, using timer 1 for hardware-timed bit toggling is likely to produce better results than code using delays based on calls like delayMicroseconds(), primarily because of overhead causing poor resolution or jitter.
Using timer 1 in a PWM mode offers an advantage: loading of the OCR1A register is double buffered in PWM modes.  This makes it possible to smoothly transition from one frequency to another without glitches due to setup delays.  The code shown below (program freqSweep.ino) illustrates one way of steadily ramping the period of a waveform.  The initial count, delta count, and number of steps parameters ic, dc, ns also are double buffered, with the first set loaded via rampInit (), and new sets loaded opportunely from time to time via rampNext ().
In operation, the ramper causes timer 1 to produce a waveform with half cycles of lengths ic, ic+dc, ic+2dc, ... ic+(ns-1)dc.  That is, it generates ns steps of varying lengths, using timer 1 interrupts to trigger its execution in the background.  While the ISR produces a ramp of cycles, the user's loop() code can be computing parameters for the next ramp.  Note, if dc>0, periods grow larger so the frequency ramp descends.  If dc<0, periods grow smaller so the frequency ramp ascends. If dc==0, the ramp is flat.  Note, ic and dc are 32-bit fixed-point numbers, with 16 binary places.  Thus, while hardware only generates time intervals with integral numbers of cycles, the ramper software works with fractional values, so dc can have values like 0.5, 3.375, .076171875 (39/512) etc.
By generating a seamless series of small ramps, one can accurately approximate larger patterns of frequency ramps.  For example, to generate a frequency-linear ramp from say 100 Hz up to 48 KHz in 10 seconds, one might divide that time into 100 parts.  If f(t) denotes the frequency desired at time t, one would then (for each 0.1 second time step) compute half-periods p and q corresponding to frequencies f(t) and f(t+0.1).  About n = 0.1*f(t+0.05) cycles are available in 0.1 seconds for frequencies between f(t) and f(t+0.1), or about ns = 2*n half-cycles.  Choose dc = (q-p)/ns [using 32:16 fixed point arithmetic, and noting that dc can be negative] to smoothly ramp from frequency f(t) to f(t+0.1) in ns steps that take about 0.1 seconds total.  0.1 seconds, or 100 ms, is enough time to calculate and load a new set of parameters.  See program comments (under the heading General form of use of ramper) re computing parameters.
Here is the example program:
// Sweep a frequency, on dig. pin 7, PD7 - jw 27 Sep 2016
#include <Streaming.h>

enum { outpin=7, mOutpin=1<<7 }; // Arduino dig. pin# & its bit mask
void setup() {
  pinMode(outpin, OUTPUT);
}

long RAMdcl, RAMdcn;    // dc is signed to allow ramps up or down
unsigned long RAMicl, RAMicn;
unsigned int RAMnsl, RAMnsn;
volatile unsigned int RAMrampsDone; // Number of ramps done so far
volatile byte RAMsendPars;  // Flag is 1 when ok to send params

void rampInit(unsigned long ic0, unsigned long dc0, unsigned long ns0, byte clockSource) {
  /* clockSource should be a 3-bit number, from 0 to 5:
   ..Bits.. ....Effect....   [See Table 16-5, p. 134 in specs]
    0 0 0   No clock source (Timer/Counter stopped).
    0 0 1   IOclock / 1    (No prescaling)
    0 1 0   IOclock / 8    (From prescaler)
    0 1 1   IOclock / 64   (From prescaler)
    1 0 0   IOclock / 256  (From prescaler)
    1 0 1   IOclock / 1024 (From prescaler)
  */
  TIMSK1 = 0;           // Turn off timer 1 interrupts
  // ic and dc (initial count and delta count) values
  // are 32:16 fixed point values; ie with 16 binary places.
  RAMicl = RAMicn = ic0;
  RAMdcl = RAMdcn = dc0;    // Set initial param values
  RAMnsl = RAMnsn = ns0;
  RAMrampsDone = 0;     // No ramps done yet
  RAMsendPars = 1;      // Next param set can load

    // Set timer 1 to Fast Pwm mode with OC1A (dig pin 9) toggling
  TCNT1 = 0;           // Zero the counter
  TCCR1A = 1<<WGM11 | 1<<WGM10; // for Fast Pwm with TOP from OCR1A
  OCR1A = (uint16_t)(RAMicl >> 16); // Initial TOP = integer part of icl
  TCCR1B = 1<<WGM13 | 1<<WGM12 | // for Fast Pwm with TOP from OCR1A
           clockSource;    // Start timer 1 with selected prescale
  TIMSK1 = 1<<TOIE1;       // Enable timer 1 overflow interrupt at TOP
}

// timer 1 overflow interrupt handler
ISR(TIMER1_OVF_vect) {
  OCR1A = (uint16_t)(RAMicl >> 16); // Update TOP with integer part of ic
  PIND = mOutpin;         // Toggle the output pin, eg dig pin 7, PD7
  // (Output bits toggle when a 1 is written to their input port bit)

  RAMicl += (unsigned long)RAMdcl;  // dc is signed but we need bare bits
  --RAMnsl;
  if (!RAMnsl) {        // Go on to next section?
    RAMicl = RAMicn;
    RAMdcl = RAMdcn;        // Set next param values
    RAMnsl = RAMnsn;
    ++RAMrampsDone;     // We are in the last half cycle of section
    RAMsendPars = 1;        // Ready for next param set
  }
}

// rampNext() busy-waits until it can load new param values
void rampNext (unsigned long ic, unsigned long dc, unsigned int ns) {
  while (!RAMsendPars) {}
  RAMsendPars = 0;
  RAMicn = ic;
  RAMdcn = dc;      // Set next param values
  RAMnsn = ns;
}

// rampStop() stops the ramp-processor, right now
void  rampStop() {
  TIMSK1 = 0;           // Turn off timer 1 interrupts
  RAMrampsDone = RAMsendPars = 0;
  digitalWrite(outpin, LOW);    // Turn off output bit
}

/*
  // General form of use of ramper:
  ...
  rampInit(icj, dcj, nsj, scaleBy1);  // Send first param set
  for (byte j=0; j<rampSections; ++j) {
    // Compute next param set ...
    icj = ...
    dcj = ...
    nsj = ...
    // Do other stuff here
    // ...
    // rampNext will busy-wait while sendPars is clear
    rampNext (icj, dcj, nsj);
  }
  // Busy-wait while last ramp finishes
  while (RAMrampsDone <= rampSections) {}
  rampStop();       // Stop the ramp-processor
*/

// Example: Play a sound with 5 ramp parts in loop(), with brief pauses
void loop() {
  enum { scaleBy1=1};
  unsigned long icj, dcj;       // My ramp param calc vars
  unsigned int nsj=1000;        // # of steps per ramp
  icj = ((unsigned long)1600)<<16;  // ic = initial count
  dcj = ((unsigned long)1)<<16;     // dc = step size
  nsj = 5000;
  rampInit (icj*3, dcj/2, nsj, scaleBy1);
  rampNext (icj, dcj, nsj/3);
  rampNext (icj*2, -dcj, nsj/2);
  rampNext (icj*2, -dcj, nsj/2);
  rampNext (icj, dcj, nsj/3);
  while (RAMrampsDone < 5) {};
  rampStop();           // Stop the ramp-processor
  delay(2500);          // silence-separator
}

This is great! A few suggestions: 1) You can have the timer generate the output on OC1A = PB1 = digital 9 by setting COM1A0 in TCCR1A. This is cleaner than doing it in software, as your ISR will sometimes be delayed by, e.g. TIMER0_OVF. 2) Putting (ic, dc, ns) in a struct makes the source better structured and the compiled code more compact: it saves 104 bytes of flash. 3) The dc0/dc arguments to rampInit() and rampNext() should be signed, and ns0 of rampInit() should not be long. 4) The casts to uint16_t on lines 37 and 45, and to unsigned long on line 49 serve no purpose.

@EdgarBonet, thanks for the comments! 1) Yes, I wanted to do that, to avoid jitter, but probably had COM1A1 set by mistake instead of COM1A0.  2) I'll try that -- it will be (ic, dc, ns, cs) where cs is clock source -- I think I've figured out how to change cs without glitching part of a cycle.  3) Agreed, noticed those inconsistencies a few hours after posting. 4) Ok.  Anyhow, I'll revise the posted code in a couple of days - work is in the way at present

There are three points:

Try to work in the terms of pulse duration. 48 000 Hz will give say 167 ticks for 8 MHz clock (83 ticks for HIGH level on active pin and 83 - LOW). Division on fly is very time consuming, so better to use period instead of frequency. 0 - switch the timer off. 1 Hz - 8 000 000 ticks (4000000 for High and 4000000 for LOW).
As I understand the stepper motor will have to drive some load, so acceleration needed depends not only on the parameters of motor itself but on the total mechanical system. So, to calculate needed data from the scratch will be rather difficult and inaccurate. Better try to calibrate the system. Tat will take a piece of job but will be more accurate.
You do not need to make smooth decrease of period but you can use several predefined steps. This will give you two arrays t[i] for period to be set in timer and d[i] - number of steps, done with this period. The total time for the given period will be d[i]*t[i]. The total time of acceleration then will be the simple sum of time slices in the sequence i from 0 to max. So you can get it rather accurately.

It will take at least two timers - one for the period setting, other for counting periods in a time slice. After one time slice is finished you just increment array index and load new data in timers. Calibration will take to define best real data for array t[] and d[].
If you will hold in t[] half-periods, then you need to double values in d[], or taking values from t[] you can divide them by 2 (it's a simple shift so it takes little time) for one half-period is HIGH and next is LOW. The decision is up to you.

I updated the post with some code.. would this work..


text:
High errors in transmission (completely eliminated by adding delay): What's the issue?
I am using a two Arduino setup with two XBee radios. One radio is sending data and the other is receiving data. I am sending three sensor readings following a protocol which uses three bytes for each sensor reading. Byte one is sensor information, byte two is data, and byte three is for error checking. When I run the set up for about 5 minutes I get approximately 47% errors in transmission. Once one error occurs, there seems to be an avalanche of errors. However, when I add delay in between sending bytes (100ms between bytes and 1s between sensor) it works perfectly. I've tried expanding the hardware buffer, but this didn't work.
        delay(2000);

        // Calcuate weather parameters for serial and web
        calcWeather(); // Go calc all the various sensors

        // send weather out to serial port
        if (prevtemplm34_1 == templm34_1) // 2 in a row must be the same to send
        {
            Serial.write(0);
            Serial.write(templm34_1);
            Serial.write(templm34_1 ^ 0);
        }

        // send weather out to serial port
        if(prevtemplm34_2 == templm34_2) // 2 in a row must be the same to send
        {
            Serial.write(1);
            Serial.write(templm34_2);
            Serial.write(templm34_2 ^ 1);
        }

        // send weather out to serial port
        if(prevtemplm34_3 == templm34_3) // 2 in a row must be the same to send
        {
            Serial.write(2);
            Serial.write(templm34_3);
            Serial.write(templm34_3 ^ 2);
        }
        delay(2000);

The code for parsing received data is:
int readData ()
{
// There must be at least three available bytes to satisfy the protocol
// Otherwise, wait until three bytes have arrived to read anything
if (Serial.available() >= 3) {

      // Read the next three byte in the serial buffer
      incomingByteOne = Serial.read();
      Serial.write("Byte One: ");
      Serial.write(incomingByteOne);
      Serial.println();
      incomingByteTwo = Serial.read();
      Serial.write("Byte Two: ");
      Serial.write(incomingByteTwo);
      Serial.println();
      incomingByteThree = Serial.read();
      Serial.write("Byte Three: ");
      Serial.write(incomingByteThree);
      Serial.println();

      // XOR the first and second incoming bytes so that the result can be checked against the third error checking byte
      byte xorValue = incomingByteOne ^ incomingByteTwo;
      Serial.write("XOR VALUE: ");
      Serial.write(xorValue);
      Serial.println("Number of Errors: ");
      Serial.println(numberOfErrors);
      Serial.println();
      Serial.println();
      if(xorValue != incomingByteThree) {
        numberOfErrors++; // Add one to the total count of number of errors in transmission
      }
      else {
        // Mask for retrieving the five rightmost bits from incomingByteOne (00011111)
        byte maskForSensorNumber = 0x1f;

        // Shift incomingByteOne right 5 times in order to obtain the three bits representing the unit number
        int unitNumber = incomingByteOne >> 5;

        // AND incomingByteOne with the mask in order to retrieve only the five righmost bits representing the sensor number
        int sensorNumber = incomingByteOne & maskForSensorNumber;

        // Store the data for the correct sensor on the correct unit
        data[unitNumber][sensorNumber] = incomingByteTwo*1;
     }
}
}

What could be causing the transmissions to work fine with delay, but not otherwise?

You are probably just transmitting too fast.
Your receiver is writing at least 80 bytes of debugging information (if
I counted it right) for every 3 bytes of incoming data. Since both input
and debug output happen at the same baud rate, this means the receiver
can only cope with an input data rate equal to 3/80 = 3.75% of
the nominal baud rate.
I would expect no errors at the very beginning of the program run,
because the debugging info is written to a RAM buffer. Only when that
buffer fills up the receiver is slowed down by every Serial.write()
and Serial.println() it performs.

Thanks @EdgarBonet. When I expanded the receiving and transmitting buffers of the receiver unit to 1,024 bytes, I still had errors after just 7 or so transmissions (just under 600 bytes including debugging). Do you think adding delay is probably one of the better ways to fix this?

@tpm900: Yes, or maybe show less debugging info.

I actually only added the debugging after I saw issues with the transmissions. However, I do have approximately 100 writes to a Client (e.g. client.println("..."). Does this also affect the buffer?

I do not know what your client looks like, but it is likely that the println() can block.


text:
SD card example freezes at line SD.begin() what should I do?
I have a 16GB SD card which is formated with FAT32. I'm trying to run the example codes presented for SD in Arduino. The SD card is inserted in the data logging shield and the CS pin in this shield is connected to pin 10.
I first tried the Cardinfo example and this is the result:

The SD card is not empty, there exist a few files in it but this example was unable to show this files.
I then tried the example ReadWrite and the code freezes on line SD.begin(10).
I have no Idea where this problem is coming from.

try the card without files on it

I tried this, it doesn't work. The Cardinfo example can detect it but can't read the system file. The ReadWrite example freezes on SD.begin() line.

I had the same problem when I used a big SD card, maybe because some cards have a more modern format.
If you have smaller / older cards, try them and see if those work; than you rule out it is not a circuit/connection problem.

It is difficult to find an SD with lower capacities. But I search maybe that is the problem.

I think I had that problem about 2 years ago too when I tried a bigger SD card.

I found another SD card with 16GB capacity, but fortunately, it worked!

Good to hear your problem is solved ... maybe the smaller SD card I tried has the same properties as your working card ... still wondering what the exact specifications should be.. But glad you found one that worked.

Thanks for you help, I appreciate it.

I found another SD with 16GB capacity, and fortunately it worked. So the problem was because of the SD but I don't know what was the exact problem. I post the photo of this SD cards.

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


text:
Communication between Genuino Zero and Arduino Uno using UART
I want to make my Arduino Uno and Genuino Zero communicate using UART. My Genuino Zero is the transmitter and the receiver is the Arduino Uno.
For the Arduino Uno, I am using the SoftSerial library. I have uploaded the transmitter and receiver codes.
My connection is as below:

Genuino Zero (RX) pin 0 ---------------- Arduino Uno pin 11
Genuino Zero (TX) pin1  ---------------- Arduino Uno pin 10
Ground ----------------------------------   Ground

The Arduino Uno's pin 10 is Rx and pin 11 is Tx, using SoftSerial.
The transmitter transmits 'a'. The receiver receives 'a' and turns a LED on. My problem is that on the receiver, I am not getting anything.
My code is here:
https://www.dropbox.com/s/4w8o2h2k4zs0it5/transmitter.txt?dl=0
https://www.dropbox.com/s/d50uizoz3iove9w/receiver.txt?dl=0
-------------------receiver---------------------
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX

/* Simple Serial ECHO script : Written by ScottC 03/07/2012 */

/* Use a variable called byteRead to temporarily store
   the data coming from the computer */
byte byteRead;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(9600);
   mySerial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  char a[8];
  /*  check if data has been sent from the computer: */
  if (Serial.available()) {
    /* read the most recent byte */
    byteRead = Serial.read();
    Serial.print("rushin\r\n");
    /*ECHO the value that was read, back to the serial port. */
    if(byteRead == 0x61) {
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.write(byteRead);
    }
  }
  if (mySerial.available()) {
    /* read the most recent byte */
    byteRead = mySerial.read();
    mySerial.print("rushin\r\n");
    /*ECHO the value that was read, back to the serial port. */
    if(byteRead == 0x61) {
      digitalWrite(LED_BUILTIN, HIGH);
      mySerial.write(byteRead);
     }
  }
}

-------------------transmitter----------------------------------

/*
  DigitalReadSerial
 Reads a digital input on pin 2, prints the result to the serial monitor
 This example code is in the public domain.
 */

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 7;
// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println("a");
  delay(1000);
  // delay in between reads for stability
}

Post the code here. Links tend to disappear.

sorry. can't upload text file here. and link is ok

Just copy paste the code here and format it into code block.

What does the product information say? "Unlike most Arduino & Genuino boards, the Zero runs at 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. Applying voltages higher than 3.3V to any I/O pin could damage the board."

yes i know that. and i am working with 3.3 v

And the Uno? How did you connect that? At least pin 11/TX would be 5V if you have not used any signal conversion.

Your receiver code won't say anything to the PC in response to data over the software serial - you only send the indication back on that.  Likely you want to send some indication to the PC instead or as well.  Also be wary of triggering messages that are longer than the ones sent, as they will take more time to transmit and could lead to missing new incoming data.

Your Arduino Zero transmitter code transmits to the USB Serial ('Serial') only. If you want it to transmit to the serial comm on pin 0 and pin 1, you must have it write to Serial1. (Check variants.cpp file ) you will see that Serial1 is uses SERCOM0 which is on pin 0 and 1.
So, Your code should look like this (noitce "Serial" is replaced with "Serial1"):
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial1.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial1.println("a");
  delay(1000);
  // delay in between reads for stability
}

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


text:
Any idea why my LED fails to operate with the if statement
I have tried several workarounds without success.
#include <LiquidCrystal.h>
float tempC;
int tempPin = 0;// BS E D4 D5 D6 D7
int buzzer = 4;
int LED =2;
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
unsigned char i;
void setup()
{
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("Temp        C ");
pinMode(LED, OUTPUT);
pinMode(buzzer,OUTPUT);//initialize the buzzer pin as an output
}
void loop()
{
tempC = getTemperature();
lcd.setCursor(6, 0); // Display Temperature in C
lcd.print(tempC);
delay(500);
}
float getTemperature()
{
int tempReading = analogRead(tempPin); // This is OK
double tempK = log(1000000.0 * ((1024.0 / tempReading - 1)));
//Temperature in Kelvin
tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK );
return (tempK - 273.15);

if (tempC>0)
digitalWrite(LED,HIGH);
else
digitalWrite(LED, LOW);
}

two possible reasons ... 1. the led is incorrectly connected and it does not light no matter what you do ... 2. the if statement evaluates to a result that does not turn on the led

I edited your question and used the {} button for code formatting, but your code doesn't have any indentation. You need to edit your code to use proper indentation. Without that it is very hard to read.

Your code to look at temperatures is messed up. You have a global variable tempC. The function getTemperature() doesn't change the value of tempC, but it uses it to decide if the LED should be lit or not. That means that that function will make it's decision based on the previous value of tempC.

You should rewrite your getTemperature() function to put the Celsius temp into a temporary variable, use that to decide what to do with the LED, and then return the temporary value. That way getTemperature() will set the LED based on the just-calculated temp value, not on the old, now-out-of-date temp reading.

Also note that if tempReading is 0, your code will crash with a divide-by-zero error. You should add some error handling code to deal with that case.

The LED fails to operate with the if statement because calling the return statement Terminates a function and returns a value from a function to the calling function, if desired. Try your sketch with the return statement as the "last thing" in the function.
#include <LiquidCrystal.h>

float tempC;
int tempPin = 0; // BS E D4 D5 D6 D7
int buzzer = 4;
int LED = 2;
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
unsigned char i;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Temp C ");
  pinMode(LED, OUTPUT);
  pinMode(buzzer,OUTPUT);//initialize the buzzer pin as an output
}

void loop() {
  tempC = getTemperature();
  lcd.setCursor(6, 0); // Display Temperature in C
  lcd.print(tempC);
  delay(500);
}

float getTemperature() {
  int tempReading = analogRead(tempPin); // This is OK
  double tempK = log(1000000.0 * ((1024.0 / tempReading - 1))); //Temperature in Kelvin
  tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK );
  if (tempC>0) digitalWrite(LED,HIGH); else digitalWrite(LED, LOW);
  return (tempK - 273.15);
}

If that code fix doesn't work I suggest you write a sketch that forces the LED to high, delays, forces it to low, delays, and loops. See if the LED flashes. If not, you have a hardware problem with the wiring of your LED. if it does work, then you have a problem with reading your temperature sensor and need to debug that part of your project.

Thank for the assistance and responses.  It does appear as if I have a physical problem of some kind.  My LED did function after shifting my breadboard a bit.  My temperature value constantly fluctuates sporadically and applying heat to my thermistor does not result in changes in the displayed temperature value. However the LED does illuminate when values rise above the limit which means the code is good.  Thanks again

Thanks Duncan.  You have been of great assistance and I certainly have a lot of learning to do and I look forward to it :)

One of the challenges of building Arduino projects is that you have to debug hardware and software problems. Work in steps. Hook up an LED, write a sketch that toggles the output pin on and off on a timer, and make sure that it works. After that, you know the LED works. Then integrate that working LED pin into your code, and if the code doesn't work, you know it's a code problem, not a hardware problem. If you get screw results from your code, add a bunch of Serial.println() statements displaying the values as you go along until you find your problem


text:
Arduino random LED on
I have a project which has two options
No. 1 Randomly turn on one LED from a group of 6 LED (Relay Board)
No.2 randomly turn on one LED from a group of 2 LED (Relay Board)
The selection of the desired option happens with a switch.
I found this code online which is just perfect for 6 LED but I don't know how to add the selection of the options in it, how to do it?
int timeShowRandom = 3000;
int timeShowDecision = 6000;
int timeBlink = 100;
int buttonPin = 2;
int buttonPress = false;
int randomNumber;
int previousNo = 0;
int timePassed = 0;

void setup() {
  // Set button pin
  pinMode(buttonPin, INPUT);
  // Set output pins
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
}

void getRandomNo() {
 int rand = random(7,13);
  if (rand == previousNo) {
   getRandomNo();
  } else {
    randomNumber = rand;
    previousNo = randomNumber;
  }
}

void loop() {
 if (digitalRead(buttonPin) == HIGH && buttonPress == false ) {
     buttonPress = true;
  } if (buttonPress == true && timePassed <= timeShowRandom) {
    getRandomNo(); // Get random pin number
    digitalWrite(randomNumber, LOW);
    delay(timeBlink);
    digitalWrite(randomNumber, HIGH);
    delay(timeBlink);
   timePassed = timePassed + (timeBlink * 2);
  } else if(buttonPress == true) {
    digitalWrite(random(7,13), LOW); // Set random pin on
    delay(timeShowDecision); // For x seconds
    buttonPress = false; // Set button to be enabled again
    timePassed = 0;
  }
  else {
    // Reset all output pins
    digitalWrite(10, HIGH);
    digitalWrite(11, HIGH);
    digitalWrite(12, HIGH);
    digitalWrite(9, HIGH);
    digitalWrite(8, HIGH);
    digitalWrite(7, HIGH);
  }
}

LEDs?  Or relays?  You seem to use both terms.  They’re not the same thing.

Various suggestions:
Create 2 different arrays of pin numbers: 1 for the first group of relay pins, and the 2nd for the second group of relay pins:
byte firstRelayPins[] = [7, 8, 9, 10, 11, 12];
byte secondRelayPins[] = [13, 14]; //Replace values with your relay pins

Write a function that returns a random index from one or the other of the arrays based on a bool:
byte randomPin(bool useSecondArray) {
    int max;
    int index;
    if useSecondArray {
       return secondRelayPins[random(sizeof(secondRelayPins))]; //Fetch random pin from array
    } else {
       return firstRelayPins[random(sizeof(firstRelayPins))]; //Fetch random pin from array
    }
}

Based on the state of your switch, set useSecondArray when you call that function to determine which relay's pin you turn on.
Use the returned value to set the desired relay pin.
In your "turn everything off" code, use the arrays of index pins rather than hard-coded indexes.
You should also refactor your code to use millis() rather than using delay(). (Search on "Arduino blink without delay" for guidance on how to do that.)
Note that this is a rough outline of what to do. The code above will likely need to be adjusted to fit your needs. Don't expect to be able to copy/paste it into your project.

Does that help?