text:
VirtualWire send function
I am a little confused on how exactly VirtualWire's "send" function works. After looking at the code, the process I gathered is the following.

In the Arduino IDE, call vw_send() with the right parameters.
Inside this method, it will start to encode the message and create the packet.
Then before the function returns, it calls vw_tx_start().
Inside that function, it enables the transmitter hardware and sets the variable "vw_tx_enabled" equal to true. Then this function returns, followed by the immediate return of vw_send(). So there is no where in this flow where the message is actually being sent.

However, the actual transmission of the message happens inside vw_Int_Handler(). But this function is never called in vw_send() or vw_tx_start(). So the only way this could be happening is if there was some sort of multi-threading correct? Because by setting vw_tx_enabled to true, the transmission process would begin inside vw_Int_Handler.
Can someone explain/clarify this?
Moreover, this library uses digitalWrite to transmit the bits. Wouldn't it just be faster to toggle the bits at the registry level?
Lastly, in VirtualWire, they send a 36 bit preamble, I assume this is for synchorinzation purposes. So if I want to send 128 byte packet length, how much of a preamble should I use? I believe the reason for VirtualWire only transmitting 27 byte packet length is because the 36 bit preamble will only keep the data synchronized for that long. So is there a certain formula used to determine the preamble size?

However, the actual transmission of the message happens inside vw_Int_Handler(). But this function is never called in vw_send() or vw_tx_start(). So the only way this could be happening is if there was some sort of multi-threading correct? Because by setting vw_tx_enabled to true, the transmission process would begin inside vw_Int_Handler.

The vw_Int_Handler function is called from the interrupt handler of one of the timer modules in the chip. Yes, you could say it was some form of multi-threading in that it happens interleaved with the main processing of your sketch.

Moreover, this library uses digitalWrite to transmit the bits. Wouldn't it just be faster to toggle the bits at the registry level?

Yes it would, but it would be less portable.  VirtualWire has been written to work on a wide range of chips, and doing low-level port access would make the code about 1000x more complex, having to include special code for each and every chip it runs on.  Easier (though less efficient) to just use digitalWrite().

Lastly, in VirtualWire, they send a 36 bit preamble, I assume this is for synchorinzation purposes. So if I want to send 128 byte packet length, how much of a preamble should I use? I believe the reason for VirtualWire only transmitting 27 byte packet length is because the 36 bit preamble will only keep the data synchronized for that long. So is there a certain formula used to determine the preamble size?

VirtualWire uses a coding system called 4b/6b (actually a sub-set of 5b/6b coding). In that system it takes 6 symbols to transmit 4 bits. It is a way of encoding the clock into the signal in a reasonably efficient manner.
The encoding system means that there can never be 36 alternating 1/0 bits in a message. That unique stream is used as the synchronisation because it can't be confused with anything else.  From then on it's just data encoded as 4b/6b. The limit on how much data can be transmitted in one packet is a purely arbitrary value. Since this is a low-speed protocol to low-power devices it is expected that they will have limited RAM, and so limited space to receive data. So small packets are the default.
The numbers in use, incidentally, have been chosen because they fit into the 4b/6b coding scheme quite nicely.  For instance 36 symbols of preamble is equivalent to 24 bits of data. The packet size is 30 bytes, three bytes of which are used for control information (checksum, byte count, etc), leaving 27 bytes of actual payload.  30 bytes is 240 bits, which is, in 4b/6b, 360 symbols. 360 symbols could be packed cleanly into 45 bytes for simple transmission (pre-encoding from binary to 4b/6b before transmission).
Other values won't fit quite so neatly.


text:
how to create a specific buffer when there is no buffer message in the data packet?
So I'm trying to understand a read method. In this method,
// Read data from buffer
int SoftwareSerial::read()
{
if (!isListening())
  return -1;

// Empty buffer?
if (_receive_buffer_head == _receive_buffer_tail)
  return -1;

// Read from "head"
uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
_receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
return d;
}

it looks it receives buffer head. But in the write only a 1 or 0 is being sent as the data packet's header. Nothing else. So how does the arduino know how big of an buffer to create?
also, there is no stop bit being transmitted, so how does it look at a buffer tail? Or is this all created regardless of the transmitter? and then, all the values just get read into the buffer, and then read again from there? Also I don't see a delay in this read method. Wouldn't that cause errors in the data flow? How is that being handled?

That read method just retrieves bytes that have already been received from an internal buffer.
The buffer is pre-allocated to a specific size (64 bytes) and that is how many bytes can be received before you start to lose data as it gets overwritten.  You have to be sure to read your data from the buffer before it overflows.
The function that actually receives each UART bit from the IO port, builds them into bytes, and stores them in the internal buffer, is this one:
void SoftwareSerial::recv()
{

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Preserve the registers that the compiler misses
// (courtesy of Arduino forum user *etracer*)
  asm volatile(
    "push r18 \n\t"
    "push r19 \n\t"
    "push r20 \n\t"
    "push r21 \n\t"
    "push r22 \n\t"
    "push r23 \n\t"
    "push r26 \n\t"
    "push r27 \n\t"
    ::);
#endif

  uint8_t d = 0;

  // If RX line is high, then we don't see any start bit
  // so interrupt is probably not for us
  if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  {
    // Wait approximately 1/2 of a bit width to "center" the sample
    tunedDelay(_rx_delay_centering);
    DebugPulse(_DEBUG_PIN2, 1);

    // Read each of the 8 bits
    for (uint8_t i=0x1; i; i <<= 1)
    {
      tunedDelay(_rx_delay_intrabit);
      DebugPulse(_DEBUG_PIN2, 1);
      uint8_t noti = ~i;
      if (rx_pin_read())
        d |= i;
      else // else clause added to ensure function timing is ~balanced
        d &= noti;
    }

    // skip the stop bit
    tunedDelay(_rx_delay_stopbit);
    DebugPulse(_DEBUG_PIN2, 1);

    if (_inverse_logic)
      d = ~d;

    // if buffer full, set the overflow flag and return
    if ((_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF != _receive_buffer_head)
    {
      // save new data in buffer: tail points to where byte goes
      _receive_buffer[_receive_buffer_tail] = d; // save new byte
      _receive_buffer_tail = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
    }
    else
    {
#if _DEBUG // for scope: pulse pin as overflow indictator
      DebugPulse(_DEBUG_PIN1, 1);
#endif
      _buffer_overflow = true;
    }
  }

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Restore the registers that the compiler misses
  asm volatile(
    "pop r27 \n\t"
    "pop r26 \n\t"
    "pop r23 \n\t"
    "pop r22 \n\t"
    "pop r21 \n\t"
    "pop r20 \n\t"
    "pop r19 \n\t"
    "pop r18 \n\t"
    ::);
#endif
}

To show you how the timing of the routine works, here is a little diagram:

Hello, i had a couple questions about that above code. So, when it says, " If RX line is high, then we don't see any start bit, so interrupt is probably not for us" in the comments, does that mean that if there is no startbit being detected, interrupts are turned off and if there is a startbit, then it is turned on? Also, what does 1/2 of a bit width refer to? Is that a time reference?

I know this is a old post, but can you clarify here?

The recv() function is triggered by the change interrupt (PCI) detecting the RX line has changed state - that is gone HIGH to LOW, or LOW to HIGH.  It responds to both changes, and also to other pins as well as the RX pin (if others are configured for PCI). So it checks to see if the RX pin is LOW (or HIGH with inverse logic) so it knows if it's an active start bit or not. If it is then it goes on to receive the entire byte, which it does by the use of tuned delay times.

Each bit has a specific time of 10/baud seconds (9600 baud is 10/9600 = 1.042ms) and that is how long each bit takes to transmit or receive. By waiting for half that time first the delay of 1.042ms falls in the middle of a received bit so it can reliably detect the level of that bit. If it didn't do that it would be reading the state on the border between two bits and it would be anyone's guess what the value would be that it would read,

Genius.... That's pretty clever. Thank you.

I have added a diagram to my answer to make it even clearer.

source: Stack Exchange

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

sort: votes


text:
Unable to tell if error is from receiving or transmitting end
so I am having trouble sending data using software serial's write function.
TX Code:
#include <SoftwareSerial.h>

SoftwareSerial TX(2,3);

void setup() {
  // put your setup code here, to run once:
  TX.begin(1200);
}

void loop() {
    TX.write(60);
}

Is the delay necessary?
RX Code:
#include <SoftwareSerial.h>
SoftwareSerial RX(2,3); //(rx pin, tx pin)
const unsigned int bufferSize = 100;

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

}

void printBuffer(const uint8_t *serialBuffer)
{
  //print contents of buffer
  for (int i = 0; i<100; i++)
    Serial.println(serialBuffer[i], BIN);
}

void processBytes(const uint8_t value)
{
  static uint8_t serialBuffer[bufferSize]; //buffer to hold values
  static unsigned int startPosition=0;

  if(startPosition < bufferSize)
    serialBuffer[startPosition++] = value;

  else
  {
    printBuffer(serialBuffer);
    startPosition = 0;
  }

}//end of processBytes
void loop() {

  //check if data is available in serial buffer
  while(RX.available())
  {
    //process data
    processBytes(RX.read());
  }
}

If i transmit the number 60, it prints 226 constantly for 2-3 seconds, then prints 60 for a short while, then goes back to printing 226. Am I doing something wrong with my code?
FIRST QUESTION: In the case when startPosition (in the process function) equals 100, it will call print. Print will then print 100 integers. Now, when doing that, there could still be data being transmitted from the transmitter. But the read function won't be executed until printBuffer returns, process returns, and the while loop iterates again. So during that time, couldn't some transmitted values potentially not be read?
SECOND QUESTION How come Software serial doesn't synchronize incorrectly more often? How is it being so accurate if the start bit is just a single bit and it's a 0. So for instance, if payload has some 0s, how come one of those 0s aren't being assumed to be the startbit? How does this get resolved? I looked at the software serial library, but I am not able to find out why. Any guidance here?
THIRD QUESTION Other than getting the startbit syncing right, are there other ways to sync the data? I was reading of NRZ encoding, manchester encoding, etc. Can any of these be implemented here? Also, would it be wise to alter the softwareSerial library to have more than one startbit?
Any guidance would be very appreciated! Thank you so much!
This is all being done with wireless RF modules.

Q2: RS232 serial idles high (aka Mark state). A transition to low (aka Space state) signals the beginning of a frame. It is assumed (read: part of the spec) that the two systems' clocks accurate enough to stay well-enough synced for the duration of a frame.  Q3: There are other serial protocols including synchronous ones, and others could probably be adapted. But what problem are you trying to solve by doing so?

Q2: Sorry I am mistaken, but isn't RS232 for wired connection mostly? And since this is wireless, i believe it idles low? Plz correct me if I am wrong.  I could be mistaken. Also, when transmitting at high speeds, the device doesn't have that much time to "idle" at either state, because the next frame will already begin to  transmit right?

Q3: The reason I am trying to use UART instead of synchronous communication is, synchronous utilizes a clock signal which is constantly being sent, therefore there will be greater battery consumption and the bandwidth might not be fully utilized for the data frame. My end result is to have a very very battery efficient mesh network using RF modules that works efficiently even when placed amidst medium disturbance(using error correction code) and is able to transmit large data packets quickly. I want it to be cost-effective and power-effective. I am demoing it on these modules first.

And since this is wireless, i believe it idles low? - whether or not it is wireless is irrelevant. Why do you believe this?

How come Software serial doesn't synchronize incorrectly more often? How is it being so accurate if the start bit is just a single bit and it's a 0. So for instance, if payload has some 0s, how come one of those 0s aren't being assumed to be the startbit? - because there should be a nice big gap between the start of a transmission (which your sending code does not now have). Assuming you have a gap long enough, the first 0 will be the the start bit, it then clocks in 8 characters, and then the stop bit, which is a 1, which makes sure that you don't mistake it for another start bit.

Once the byte starts being received, any internal 0 bits are not considered start bits. Read my page about serial comms - you seem to not understand the process in general. Also, would it be wise to alter the softwareSerial library to have more than one startbit? - no, because you would then have no alternative but to ignore the second one. You are thrashing around with these suggestions.

I was reading of NRZ encoding, manchester encoding, etc. - certainly there are other ways of transmitting data, remote controls and remote-controlled vehicles use other methods than serial. This now is making this question extremely broad.

The "idles low" comment was w/ respect to the comment by JRobert, and before I actually had some amount of delay in the TX code. But is there a methodical way to estimate exactly how much the delay should be? And for the "longer start sequence" suggestion, I read that often times the start bit is actually a sequence, not just 1 bit. In a separate post, someone told me that exactly. That, typically, it's longer than just a bit.

For the synchronization question, I wanted to get a feel of how to implement such a thing, regardless of if it will be apt. Specifically NRZ encoding. Sorry! I really don't mean to sound ignorant or rude. Please forgive my foolishness. I will do more reading on serial comm.

Also if ample gap is what is required the start bit to be correctly recognized, then why is there the following scenario. I had asked this in a pervious question regarding delays. But to reiterate, when I transmitted with delays of microseconds, it was very low error rate, and delay of 3 or more was more error. And I read your explanation on the error rate based on how long NOP instructions take and the rounding down of the delay time/instruction time. However, based on the comment that you informed me now, shouldn't 3 microsecond delay potentially give better results?

@NickGammon Hello, should i make the above questions a new question?

In a separate post, someone told me that exactly. - where did they say that? Link? The start bit has to be exactly one bit length or the timing of everything else would be out.

should i make the above questions a new question? - your question about Manchester and NRZ vs Serial should be a new question, certainly. And your questions about start bit length seem to me to be another question again. This question started off being about "why doesn't this code work?" and is now morphing into "how does serial comms work, exactly?".

void loop() {
  Serial.println("NEW-------------");
  int x;
  int y[100];
  for(int i = 0; i<100; i++){
    x=RX.read();
    y[i] = x;
  }
...
}

You are reading data without checking if there is any data there. That's like watching the TV without checking if it is turned on. Of course you get weird data.

SoftwareSerial RX(0,1); //(rx pin, tx pin)

Pins 0 and 1 are used by HardwareSerial. Why are you using them for SoftwareSerial?

SoftwareSerial RX(0,1); //(rx pin, tx pin)
...

  Serial.begin(9600);
  RX.begin(1200);

So you initialized HardwareSerial, which now controls pins 0 and 1.
Then you try to initialize SoftwareSerial on those same pins! Would you mind explaining why?
Whatever your explanation is, it won't work.

I've added in the changes you mentioned, but the data still seems to be skewed.

You've changed things, for sure:
 for(int i = 0; i<100; i++){
    if(RX.available())
      x=RX.read();

    y[i] = x;
    }

Let's see. In a loop of 100 iterations you see if anything is available (and if so, put it into x).
Then, regardless of whether or not you got anything you now assign x to y[i]. So, most of the time, y[i] will have garbage in it.

the data still seems to be skewed

Not surprised. Do it differently. Only write to the array if you have data. In fact you may want a complete rework. Read this:
How to read serial without blocking

I have posted the amended code. Change: Only add to the array is data is being read from buffer.

  int y[100];
  for(int i = 0; i<100; i++){
    if(RX.available())
    {
      x=RX.read();
      y[i] = x;
    }
  }

 for (int j = 1; j<=64; j++){
    Serial.println(y[j]);
  }

You still have not fixed it. Let me talk you through what it is doing now.
You are making 100 attempts to read some data. One or two may succeed, and they will be put into the buffer y (funny name for a buffer, right?).
So imagine . is garbage and X is good data, after doing that loop of 100 the buffer will look like this:
........X...........X...........X...X......................X.............................................

So your buffer is still 80% unchanged garbage. Then you print the first 64 elements (why 64 and not 100?) and you get a lot of garbage out. Exactly as expected.

You need to think about what you are doing. Draw it out on a bit of paper, perhaps.
Here is some example code from the page I linked for you, more than once. Please compare:
// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

It seems to be a common misconception that you have to use software serial to talk on the TX and RX pins, and that your computer communicates with the main chip through eTelepathy.  I wish people would read the manual!

Hello sir, so i looked at your forum. At such high baud rates, the read would execute extremely fact but for ProcessIncomeBytes to execute, it would take longer than the speed at which read is reading right? and whwat else should i rework? i fixed the array part.

I don't understand any of that. The read would be faster than the read? If you fixed some code please post the amended code. At 9600 baud I would not be too worried about code execution time.

What I mean is, processIncomingBytes is called and immediately, read is also called. Then the return of read is being sent to procsessIncomingBytes. Now, processIncomingBytes will execute it's algorithm, and during that time, bits are still being sent to the buffer of the receiver. But read is not being called. So isn't there a possibility of some bytes potentially being lost if the buffer goes into overflow? Maybe not for 9600 baud, but what if i had 115200 baud? I have posted the amended code. Change: Only add to the array is data is being read from buffer.

Well, it won't go into overflow if you code correctly. Take a look at my MIDI interpreter demo (video). That is using SoftwareSerial reading at 31250 baud, interpreting it, and outputting the converted output to the screen. You can see from the video it keeps up with very fast MIDI. Please read my link How to read serial without blocking.

See amended reply.

Sorry, I didn't mean to seem like I didn't look at your link. I did look at it, and the other one you posted before hand of how to do serial communication. I just didn't quite understand. Sorry! I will try to learn it again. Thank you for your help!

Also my thinking behind why I am only printing 64 was because, the buffer only holds 64 bytes.

int y[100]; - how can you say it only holds 64 bytes?

In your code, you have up to the first 50 bytes,
then if it's overflow, we empty buffer, or if end line character
is reached, then we process/print bytes. But the 50 bytes could potentially have lots of garbage right? So is the change you're implying in my code, what i have implemented (see modified
question)? Also, there is only 64 byte serial buffer built for the UART built into the chip, which is why i had 64. But I see why that doesn't matter.

@NickGammon I have editted my question.

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


text:
High rate of transmission errors (~50%) using Xbee Radio
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. When I use the same size output and paste it all into the serial monitor I get 5 errors and all five come with the reading of the last 5 blocks of three bytes. Here is the code to send the data:
        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;
     }
}
}

It seems like the error is at least partially with my code. What could I do to reduce errors?

You seem to be using the same Serial instance / UART for both the xbee and the output of the sketch, that may be problematic - how exactly do you have things wired?.  Additionally you do not seem to have any mechanism to restore synchronization to the transmitter's 3 byte units if that is ever lost - or even not well established to being with.  Systems like this often have a header that cannot occur in the data, and look not just for a number of bytes available, but a sequence starting with the required header.

What is the serial speed you are using?

@VisualMicro 9600 baud

@ChrisStratton I am just using the Xbee on a radio shield. I was thinking my problem was what you suggested, an avalanche affect of one transmission being wrong.

How many messages are being sent per minute? When connected to the pc are errors in the last packets or at ransom times? Are both xbee at same speed? Broadcast or coordinator setup? Which Arduino IDE version?


text:
Serial Communication between 2 Arduinos for analogRead value
I have an optical sensor connected to A0 on Arduino #1 (Nano) giving me values from 200 to 1010. I need to receive these values in Arduino #2 (Nano) through serial communication. I have used a simple code for sending and receiving bytes, but I don't understand how to get the actual sensor values as int. I found some examples showing single values, but as far as I can understand variable values are more complex.
Transmitter Code:

void setup() {
  pinMode(A0, INPUT);
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
}

Receiver Code:
void setup() {
        Serial.begin(9600);
}
void loop() {
        if (Serial.available() > 0) {
        int incomingByte = Serial.read();
        Serial.print("I received: ");
        Serial.println(incomingByte, DEC);
        }
}

Maybe you should slow down the serial printing on the transmitter side. The Arduino will pretty fast fill up the whole buffer and every serial write with a full buffer will result in values, that do not get transmitted. That might also be the problem with Rudy's answer. Try adding a short delay(100);

One byte is 8 bits so 2^8 is equal to 255. One byte can hold value up to 255. Since you have value of 1023(max possible) you have to split value into two bytes.
Here's an example:
unsigned byte highValueByte(int value)
{
    return (value >> 8);
}

unsigned byte lowValueByte(int value)
{
    return (value - (highValueByte(value) << 8));
}

int giveValue(unsigned byte highByte, unsigned byte lowByte)
{
    return ((highByte << 0) & 0xFF) + ((lowByte << 8) & 0xFFFF);
}

void loop()
{
    int senValue = analogRead(/* PIN NUMBER */);
    int byteOne = highValueByte(senValue);
    senValue = lowValueByte(senValue);
}

Your code Works for one byte(try it), but it doesn't for two bytes value. Because you have two bytes, you have to introduce some kind of buffer.
Example:
unsigned byte buffer[2] = { 0, 0 };
Also be sure you connected pins properly. RX from Arduino #1 goes into TX from Arduino #2 and vice versa.
About serial communation sync

You'll want to get familiar with the standard C function sscanf().  It does exactly what you're looking for, converts an ASCII string into whatever type you like.
sscanf() API
The code to read an integer from the serial port would look something like this:
  char recv_buf[10];  int recv_int;
  Serial.readBytesUntil('\n', recv_buf, 9);
  recv_buf[9] = 0;  // make sure it's null terminated
  sscanf(recv_buf, "%d", &recv_int);
  Serial.print("I received: ");
  Serial.println(recv_int);

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


text:
Can I power 25 LED via USB?
So I'm currently working on a project where I build a WordClock. To display the current time I use WS2812B LEDs which should be white when turned on. Only about 25 leds per time will be turned on, the rest will be off. If my calculation is correct that should result in 1,5A (25leds x 60ma = 1500ma = 1,5A).
With the little power consumption of the Arduino Nano I think it won't exceed 2 amps at a time.
Is it safe to power this from a standard USB port or do I need some of the relatively overpriced (at least here in Germany) led power supply? What's the worst that could happen if I would exceed the amperage of the power supply? Would the LEDs just be dimmed or would it be dangerous in any way?
Thanks in advance

Your calculation is correct. 25 LEDs on full white will draw 1.5A.
You cannot drive this from a standard USB port on your PC. These ports can give up to 500mA (higher currents for USB3.0 ports will only be available after additional negatiations - not possible with a Nano). When powering from such a port, the port will either go into emergency shutdown (reenabling after the next reboot), or you will damage the USB port beyond repair.
But you don't need an overpriced power supply, that is meant for these LEDs. The WS2812B LEDs work on 5V, so you can use any 5V DC wallwart power supply, for example a standard USB charger, that gives you at least 2A.

What's the worst that could happen if I would exceed the amperage of the power supply?

In general you risk to damage the power supply, so that it won't work anymore. Drawing more power than allowed from a power supply is like a short, which is never good. Also too hot wires and such can cause fires.
But that is not always true. I tested a big strip of those LEDs on a simple USB charger myself one time. The charger was not rated high enough for all the LEDs. So the LEDs lit up for a very short time (like a flash) again and again with about 1s between each flash, as the USB charger tried to supply the voltage and did go into emergency shutdown again. This didn't hurt the USB charger, though I would not do this for very long. Also you cannot be sure, that your USB charger will do the same. (I also live in germany, so it might be the same case). Also look at the description of the chargers. Sometimes they write a high current into the title of multiple port chargers, but this current is distributed between the ports, so that you need multiple cables to draw the full current.
As USB chargers are quite cheap, I would suggest to use one of these. Pay extra attention to the current rating and stay well above your requirements (2A should be enough).
Very important: Be sure, that you don't draw the LEDs current through the Arduino. This would fry it's protection diode. Instead connect the LEDs power lines directly to the power supply, in parallel to the Arduino.

@Janik, you might want to check out any old phone (tablet etc) chargers that you have laying around.  The first two that I pulled out of my box delivered 2A@5V (Samsung) and 2.1A@5.1V (Apple) - and to all the "I don't like what you said - so I will down vote you people" on this site, this is the rating that is written on the charger.

Actually found a 3a@5v fast charger in my drawer, gonna use this, thanks

Cool. Just remember what chrisl said about not drawing the power through the arduino (last paragraph in the answer)

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


text:
Parsing the data from an HTTP POST request on a ESP8266 / wemos
I'm sending an HTTP Post request on my Android App to my Wemos D1 mini pro and want to parse the incoming data (which is a json). My current code just prints out the whole POST request and I need to trim it so I only get the needed data. There are several examples out there but nothing matched my needs or worked at all.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>

const char* ssid = "myssid";
const char* password = "mypassword";
char c;
String readString = String(100);
WiFiServer wifiServer(80);

void setup() {

  Serial.begin(9600);
  delay(1000);

  WiFi.begin(ssid, password);
  WiFi.mode(WIFI_STA);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting..");
  }

  Serial.print("Connected to WiFi. IP:");
  Serial.println(WiFi.localIP());
  wifiServer.begin();

}

//for parsing the actual JSON later
//you can ignore this at this moment because I don't even get the needed string to parse it from JSON
void handleReceivedMessage(String message){

  StaticJsonBuffer<500> JSONBuffer;                     //Memory pool
  JsonObject& parsed = JSONBuffer.parseObject(message); //Parse message

  if (!parsed.success()) {   //Check for errors in parsing

    Serial.println("Parsing failed");
    return;

  }

  const char * name3 = parsed["name"];           //Get name from HTTP
  Serial.println("name3");
}

void loop() {
  WiFiClient client = wifiServer.available();

  if (client) {
  Serial.println("Client connected");

    while (client.connected()) {

      while (client.available()>0) {
        //instream from mobile device

        char c = client.read();
        if (readString.length() < 100) {

         //store characters to string
         readString.concat(c);
         //Serial.print(c);
}
      Serial.print(c);
//if HTTP request has ended
       if (c == '\n') {
          //Serial.println(readString);
          delay(50);
          //handleReceivedMessage(readString);
          readString = "";
          client.stop();
   }
 }}}}

the request has a protocol part and the payload. the HTTP headers end with an empty line. then the payload, your json string, follows. the ArduinoJson can only process valid JSON, but you feed it with the complete HTTP request. a valid code would parse the headers line by line, read the content-length header and then use this length to read the payload.but a simple version could simply skip the header with client.find("\r\n\r\n"), like in this example https://github.com/jandrassy/WiFiEspAT/blob/595074cc3c17e968ae68ae2e44f448952e8b7b87/examples/Advanced/ConfigurationAP/ConfigurationAP.ino#L80


text:
how to use AckPayload correctly
i'm trying to send String from an Arduino(Uno) using the Serial. to an another Arduino(Uno). using nRF24l01+. and I'm using the library RF24.h
the String is sended correctly but I have some problems with the acknowledgement.
This is my Rx code.
#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
const uint64_t pipe[1]= {0xF0F0F0F0E1LL};
RF24 radio(9,10);
char buf[32]= "";
char false_buf[32]= "MKJK212U1H7";
void setup()
{
  Serial.begin(115200);
  radio.begin();
  radio.setChannel(0x35);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  radio.openReadingPipe(1,pipe[0]);
  radio.startListening();
  radio.setRetries(1,15);
  radio.writeAckPayload( 1, false_buf, sizeof(false_buf) );
}
void loop()
{
int OkMsg;
  while(!radio.available()){};
  if ( radio.available() > 0) {
    radio.read(&buf,sizeof(buf) );
    Serial.println(buf);
    radio.writeAckPayload( 1, buf, sizeof(false_buf) );
      while(!radio.available()){};
  if ( radio.available() > 0) {
    radio.read(&OkMsg,sizeof(OkMsg) );
    Serial.println(OkMsg);
    if(OkMsg == 1){Serial.println("OkMsg's true!");}
    else {Serial.println("OkMsg's false!");}
    }}
  }

and this is my Tx code
#include <SPI.h>
#include <RF24.h>
#include <nRF24L01.h>
RF24 radio(9, 10); // CE, CSN

const uint64_t pipe[1]= {0xF0F0F0F0E1LL};

char CharToSend[32]= "" ;
char Ack[32]= "" ;
String inputString = "";
String Allconfiguration = "";
boolean stringComplete = false;
char  inChar;
boolean isConnected = false;
int OkMsg = 0;

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

void loop()
{
  if(stringComplete)
  {
         if(Allconfiguration.startsWith("\n")){Allconfiguration.remove(0,1);}
     Allconfiguration.remove(Allconfiguration.length());
    inputString = "";
    Serial.print("Allconfiguration : ");
     Serial.println(Allconfiguration);
    int counter = 0;
    for(int i=0; i<Allconfiguration.length(); i++)
    {
      if((Allconfiguration[i] == '\n')&&(i!=Allconfiguration.length()))
      {
        int pre_counter = counter;
        counter = i+1;
        inputString = Allconfiguration.substring(pre_counter, counter);
        if(inputString[0]!='$'){inputString.toCharArray(CharToSend,32);}

        if(radio.write(&CharToSend, sizeof(CharToSend)))
        {CheckData();
       Serial.print("inputString : ");
         Serial.print(CharToSend);}
      }
       if(i == Allconfiguration.length()){
        const char EndChar[2] = "$";

       }
        inputString = "";
    }
    Allconfiguration = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
  char inChar = (char)Serial.read();
    Allconfiguration +=inChar;
     if (inChar == '$'){stringComplete = true;
    }
    }
}

void RadioSetupTransmiter(){  radio.begin();

  radio.setChannel(0x35);
  delay(100);
  radio.setAutoAck( true ) ;
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  // radio.printDetails();

  radio.stopListening();
  radio.openWritingPipe(pipe[0]);

  radio.setRetries(1, 15);
 }

void CheckData(){
  int OkMsg = 0;
    while (!radio.isAckPayloadAvailable()){};
      if(radio.isAckPayloadAvailable())
      {
       radio.read(&Ack,sizeof(Ack));
       //Serial.println(Ack);
       if(strcmp(CharToSend,Ack) == 0){
        OkMsg = 1  ;
        Serial.println("AckRecived");
        radio.write(&OkMsg,sizeof(OkMsg));}
    }
}

I have not used the RF24 libary, but below are the register settings that should be written during void setup() to use the ACK_PAYLOAD functionality (N.B. nRF24L01+ only, does not exist on nRF24L01.  Check you are using the right version of the radio!)
TX:

0x00 CONFIG = PTX mode
0x0B RX_PW_P0 = Number of data bytes in pipe 0
0x1C DYNPD = 0x01. Enable dynamic payload on pipe 0 (set DPL_P0 bit)
0x1D FEATURE = 0x06 (set bits EN_DPL and EN_ACK_PAY).

RX

0x00 CONFIG = PRX mode
0x0B RX_PW_P0 = Number of data bytes in pipe 0
0x1C DYNPD = 0x01. Enable dynamic payload on pipe 0 (set DPL_P0 bit)
0x1D FEATURE = 0x06 (set bits EN_DPL and EN_ACK_PAY).
Finally, load an initial payload using the W_ACK_PAYLOAD instruction 0xA8, i.e. SPI.transfer(0xA8); SPI.transfer(payload);.


text:
How to send SMS from an Ethernet shield via SMS Gateway?
How do I send SMS from an Ethernet shield via SMS Gateway?
The site Clickatell provides free SMS.
Does anyone know how to do this or is there some other way to do it?

you might want to be more specific that this. How far are you? What have you tried? Do you have an ethernet shield ? Do you have an arduino ?'

please say what you want to do. Then i can say how to do it.

First contact Clickatel's support and ask them how to use their API, make yourself familiar with it.
Then when you know that you connect your Arduino to your ethernet shield, I'm just gonna assume you got Arduino's original shield, because you want to support the arduino foundation.
http://arduino.cc/en/Main/ArduinoBoardEthernet if you have the standalone board.
http://arduino.cc/en/Main/ArduinoBoardEthernet if you have the shield board.

yes i have original ardunio and Ethernet shield

Open an account and try to implement their API using something like Chrome REST client. Then do the same through the ESP8266. I would personally relay it through my own web service/ url. You could also take a look at: http://www.instructables.com/id/Send-SMS-from-Arduino-over-the-Internet-using-ENC2/

Thanks to the moderator for telling me to give an improved answer, Here it goes->
From your question I infer that you want to send a SMS from your Arduino with an Ethernet Shield.
My suggestion to you is to use a service "CAYENNE".
It's a cross platform service for IOT.
You can create a FREE account on it by visiting their website :here
You will be provided with a KEY to use with your devices
Then all you have to do is connect your Ethernet Shield and upload Cayenne's BASIC code to your Arduino so that it would link the key assigned to you to the account.
You can now Control your Arduino from any APP or directly through their website as provided above.
As far as SMS is concerned all you'll have to do is to add a trigger (GO TO OPTIONS -> TRIGGERING AND ALERTS  ) and select the notify option(Add SMS here)
Then you just have to enter the country code along with the phone number and when a particular event of your choice occurs you will be notified via SMS.
Hope this helps :)
Feel free if you have any further doubts.


text:
How to call URL with Arduino Ethernet shield?
I'm working on Arduino and Ethernet shield.
I need to call a URL. How can do it? (This URL is HTTP API to send an SMS to my phone).

url:
http://api.clickatell.com/http/sendmsg?user=mohammed.atha&password=********&api_id=3539384&to=********&text=hello

You need to use the EthernetClient. link
The exemple using your API call is:
if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make your API request:
    client.println("GET /sendmsg?user=mohammed.atha&password=********&api_id=3539384&to=********&text=hello HTTP/1.1");
    client.println("Host: api.clickatell.com/http/sendmsg");
    client.println("Connection: close");
    client.println();
}

Full example from Arduino.cc docs:
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,0,177);

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

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

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make your API request:
    client.println("GET /sendmsg?user=mohammed.atha&password=********&api_id=3539384&to=********&text=hello HTTP/1.1");
    client.println("Host: api.clickatell.com/http/sendmsg");
    client.println("Connection: close");
    client.println();
  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while(true);
  }
}

how this can help me !!!
plz help me

Just look at client.connect(server, 80) in code in the example, i've changed to work with your API call.

thnx thnx thnx :D
but why use google.com as server ? (char server[] = "www.google.com";)

Is there a need for subnet and default gateway ?

This is just to check if you have internet connection, simulating a ping in the google server. If it responds you have connection and then you make your API call, you can ignore this if you don't want to check for internet connection.

You don't need the default gateway

serial monitor (connecting...
connected
HTTP/1.1 400 Bad Request
Content-Length: 54
Content-Type: text/html; charset=UTF-8
Date: Thu, 30 Apr 2015 21:40:03 GMT
Server: GFE/2.0
Connection: close
Error 400 (Bad Request)!!1
disconnecting.)
why bad request ?

vitor leal ????

@MohammedAthamneh please vote in the answer if it helped you ;)


text:
Serial to USD (HID keyboard device) converter
I am working on a project to collect data from a barcode scanner using an Arduino, which in turn is connected to a POS/laptop. So far I am able to collect the data from the barcode scanner by using the Arduino as a host, and in order to send the scanner data from the Arduino to the laptop, I am using a basic FTDI board that converts serial data from the arduino to USB.
However, it shows up as a COM port in my computer and I need an additional serial monitor to see the data transferred from the Arduino.
Is there a device that converts serial data from the arduino to "HID keyboard Device" similar to the FTDI board?
Please let me know if I have not made myself clear or if you need more information.
Edit: I forgot to add that I am using an Arduino MKR NB 1500. I am using the board's native USB port to connect to the barcode scanner. The USBHost library gives the board the ability to act as a USB host and connect to the barcode scanner and get the scanned data from the barcode scanner.
I am using the FTDI board (serial to USB converter) and arduino's serial1 to send the scanned data to my laptop.
We are trying to build a portable device that connects to the barcode scanner and the POS. We are using the Arduino to update our database (I can use the MKR board to send a POST request with the barcode data to update our database) and in addition to this the Arduino should be able to send the scanned data to POS.
As of now I am connecting the Arduino's RX and TX pins to the FTDI board, which converts UART to USB. I would like to replace this FTDI board with an interface that converts UART to "USB HID keyboard". Please let me know if more information is needed.

you could use a scanner which has SPI or Serial interface and let the USB free for keypad emulation

I would like to replace this FTDI board with an interface that converts UART to "USB HID keyboard".

On the left is an "FTDI Friend" that converts serial to USB. It is similar to the Sparkfun product you are using.
On the right is a similar sized, similar priced, board that can read serial and can act as a USB keyboard (Implementing the appropriate HID). It's a Pololu A*Star micro but it's just one example of many similar devices. I used this one to implement a physical keyboard using mechanical switches but the input could have as easily come from it's serial interface.
Any ATmega32u4 or SAMD based board can act as a USB HID keyboard using the standard Arduino keyboard library
Admittedly you'll have to write and upload a sketch but that ought to be relatively straightforward.
There are also smaller, potentially cheaper, boards such as the Digispark and clones that have a separate software library to implement USB HID Keyboard functionality on a very simple microcontroller like the ATtiny85.

We are trying to build a portable device that connects to the barcode scanner and the POS.

As Juraj's comment suggests, many barcode readers started out as serial devices and only later had USB-serial capability added. If you use a Barcode scanner with serial output, you probably don't need any extra hardware and can use the MKR NB 1500's USB interface to act as a keyboard device instead of as a host for the scanner.

Thank you so much for your response. I will try with Attiny85 and 32U4 Micro boards and see how it goes. Unfortunately, i have to work with USB barcode scanners and I am using the arduino board's native USB to get the data from the barcode scanner.

use CH9329 chip it's cheap and could act as Keyboard and mouse at the same time. interface is a little bit hard as it's Chinese but it's cost 1 USD only.


text:
How to use assembly in Arduino?
I have been assigned a university project to make a sound/audio responsive LED using assembly language. I have already wrote C++ code in Arduino that uses the Fastled library.
How do I write working code for this project in assembly (not restricted  to @rduino IDE, but preferable)? I've already tried converting my code to assembly using an online converter, but it is useless.

The Arduino IDE is quite idiosyncratic. It won't let you work on a
project that doesn't have a file with the extension “.ino”. On the other
hand, it doesn't care about how much code is in that file, and you can
keep it happy by creating an empty .ino file. I recommend however that
you put at least a comment block in that file, in order to make things
less confusing for other people who could see your project. Then you can
put your assembly code alongside this empty file, in files of their own
ending with the “.S” extension. These files will be preprocessed before
being assembled, so you can #include <avr/io.h> and use the macros
defined therein for the IO ports, bits, etc.
The project would look like this:
my_project/         # containing directory
├── my_project.ino  # comments only, to keep the IDE happy
├── my_project.S    # main assembly file
└── some_extras.S   # possibly more assembly files...

If the whole project is pure assembly, one of your assembly files should
define a symbol called main, which is the entry point of the program:
.global main
main:
    ; code starts here

If you are going to mix assembly and C++, then you can define main()
in the .ino file, and call from there your assembly routines, which
should be declared as extern "C":
extern "C" void my_assembly_routine();

int main()
{
    my_assembly_routine();
}

Mind the calling conventions when mixing asm and C++ though.
If you are going to use the Arduino core library, then you should define
setup() and loop() instead of main(). The Arduino core will then
provide it's own main(), which takes care of its initialization.
If you are going to write mostly C++, with only some assembly sprinkled
here and there, inline assembly could be a better option. C.f. Michel
Keijzers' answer.

Upvoted, much new info for me too.

Sorry.
The main learning effect of this exercise is "Don't do it".
You won't beat the c++ compiler regarding performance (speed). But you will run into more errors than you can imagine.
The only purpose of manual assembler language inside c/c++ is to add nanosecond timing by adding some asm("nop"); statements to wait a controlled small number of cpu clock cycles.
@Michel Keijzers' examples are already implemented. Even in Arduino's convenience environment.
IMO it's more challenging to get beyond Arduino programming by going directly to the MCU's hardware level, dealing with Timers, other MCU components, Registers etc. directly. In C/C++ of course. There you learn that there's much more that can be done beyond the Arduino environment.
Or: Look at compiled results via avr-objdump to learn how C++ is compiled to machine code by experts. Very eventually, you might notice how you could help the compiler optimizing.

By learning assembly, you learn a lot more than “don't do it”: you get an intimate understanding of what the compiler and the hardware do, and you learn what kind C/C++ constructs compile to efficient machine code. Also, you must have written at least a little bit of assembly to really appreciate the compiler's job (the output of avr-objdump). 2. It is not rare that avr-gcc produces sub-optimal code, easily beaten by hand-crafted assembly. I guess this flavor of gcc has not been fine-tuned as much as the ARM or x86_64...

@Edgar Bonet : Sure, you learn a lot more. And only after you've learnt that you can 1. appreciate what the compiler is doing for you 2. interpret its results 3. decide whether you'll continue with assembly programming. BTW: I came from assembly programming, because FORTRAN was not really optimal for small machines, and I'm happy since someone invented C and others built cross-compilers.

Re: "The main learning effect of this exercise is "Don't do it". You won't beat the c++ compiler..."
I agree with Edgar Bonet:
(1) Arduino is about learning, including learning Assembler programming, hardware, etc.
And ...
(2) Yes, you can beat the C++ compiler with a little practice. E.g. the GNU tool-chain can input the C++ program and output the corresponding Assembler.
This can be very instructive for learning Assembler. You can then hand-craft any bit of that code...make it faster, or smaller
--o-0--

You have to use the asm  keyword, like:
asm("sei \n")

In your case it is advised to use defines, e.g.
#define CLI()          asm("cli \n")
#define noInterrupts() cli()

#define SEI()          asm("sei \n")
#define interrupts()   sei()

See more info at arduino-inline-assembly-tutorial-1.

Which IDE do we have to use for this? Also, are these definitions for inline assembly? We are restricted to have the main working code of our program in assembly language.

Afaik the default Arduino IDE can be used for this. You probably have to put the code inside the setup and loop functions. Note however, the Arduino IDE creates some code around the setup and loop (like interrupt handling).

Wait a minute here. You can use #define for functions/methods? Well, that's new to me.


text:
Arduino Mega TIMER1 one second interval
Is this timer set correctly for Arduino Mega? It should count exactly one second. And why when I print in serial monitor (seconds_passed++) is it incremented by 2 not by 1?
Full code on Pastebin: LINK
noInterrupts();
//set and initialize the TIMER1

TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // set entire TCCR1B register to 0
TCCR1B |= (1 << CS12);
TIMSK1 |= (1 << TOIE1);
TCNT1 = 3036;

attachInterrupt(digitalPinToInterrupt(ignition_pin), ignitionSignal, CHANGE);
interrupts();

ISR(TIMER1_OVF_vect) {
  //TIMER1 overflow interrupt -- occurs every 1sec --
  instantSpeed();
  LPG_Consumption();
  LPG_injector_open_duration = 0;
  unleadedConsumption();
  unleadinj_Open_Duration = 0;
  seconds_passed++;
  vss_pulses = 0;
  TCNT1 = 3036;
}

I am not an expert on this, but Mega runs at 16 MHz. your prescaler is 256 so TCMT1 should be 16000000/256 for 1 second?

You asked a new question about the same topic, instead of improving your previous question. At least delete your previous question now

Your timer configuration is ok so far. Never the less I recommend using the TIMER1_COMPA_vect interrupt vector instead of TIMER1_OVF_vect which has the advantage of better readability (in my oppinion) and TCNT1 doesn't have to be reset in the ISR (instead, OCR1A is just initialized with 62500 once in setup()). Therefore, TIMER0 has to run in CTC (clear timer on compare match) mode and WGM12 has to be set in TCCR1B.
The reason why seconds_passed is incremented twice is because you Serial.print(seconds_passed++) in instantSpeed(). Printing on the serial interface is damn slow and using it in an ISR is a no-go!

Thanks, do you mean something like this:                                                                                TCCR1A = 0;            // undo the Arduino's timer configuration
TCCR1B = 0;            // ditto
TCNT1  = 0;            // reset timer
OCR1A  = 62500 - 1;    // period = 62500 clock tics
TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
| _BV(CS12);    // clock at F_CPU/256
TIMSK1 = _BV(OCIE1A);  // interrupt on output compare A

I can't guarantee because I don't have an atmega2560 available right now, so there might be little things to fix. What is TOP=OCR1A supposed to do? I don't think that's neccessary. Also I think, OCR1A=62500 is theoretically correct (there is no "tick" at 0), but probably you won't recognize any difference...

It is only comment.

Allright! I suggest you try this standalone by blinking an led, just to see. If it doesn't work, feel free to ask!

@Adam: Avoid writing code in comments: it's not very readable. Post a link instead. @SimSon: 1. Adam copy-pasted from this answer. 2. The timer counts from 0 to OCR1A inclusive. If you want a period of 62500, then OCR1A should be set to 62500−1=62499.

@EdgarBonet so practically resetting TCNT is one tick?


text:
Trouble with Timer 0
I'm taking my first wobbly steps outside the Arduino IDE and I'm not having much success with timers / interrupts. I can set a pin to output and light an LED with registers fine but I cannot for the life of me get it to blink using a timer. I have tried numerous tutorials and followed the Atmel ATmega328 datasheet very closely.
Using an Arduino Uno R3 & Atmel ICE (ISP.) My dev system is Raspbian (Debian) with the GNU AVR toolchain (avr-gcc, avr-objcopy, avrdude.) Apart from not having a bootloader it's a bog standard board (including fuses.)
Here's my current code:
#include <avr/io.h>
#include <avr/interrupt.h>

ISR(TIMER0_COMPA_vect)
{
    PORTB ^= (1 << PB5); // Toggle Arduino Pin #13
}

int main (void)
{
    DDRB = (1 << DDB5); // Arduino Pin #13 is Output

    cli(); // Clear Interrupts

    OCR0A = (unsigned char)0xFF; // Compare Register A = 255
    TIMSK0 = (1 << OCIE0A); // Enable Interrupt for Comp. Reg. A
    TCCR0A = (1 << WGM01); // CTC Mode

    sei(); // Set Interrupts
    TCCR0B = (1 << CS02) | (1 << CS00); // Divide by 1024 Prescaler (GO!)

    return 0;
}

I don't know if I'm just not seeing something or if I've set registers in the wrong order but it's driving me crazy.

doesn't return 0 reset the device? Try while(1); to make it wait indefinitely.

I am going to scream. Thank you!
(Do you do the Answer Question thing or do I?)

The commenter should convert it into an answer.

return 0 resets the device. Use while(1); instead, to make it wait indefinitely.

Just to clarify, doing a return from main does not reset the device, as I showed in my answer. I mention this in case people read this answer and think that returning from main is an easy way of achieving a device reset.

Returning from main does not reset the device (it would start up again and do it all over in that case). It calls exit which turns interrupts off and loops indefinitely.
00000068 <__ctors_end>:
  68:   11 24           eor r1, r1
  6a:   1f be           out 0x3f, r1    ; 63
  6c:   cf ef           ldi r28, 0xFF   ; 255
  6e:   d8 e0           ldi r29, 0x08   ; 8
  70:   de bf           out 0x3e, r29   ; 62
  72:   cd bf           out 0x3d, r28   ; 61
  74:   0e 94 52 00     call    0xa4    ; 0xa4 <main>
  78:   0c 94 61 00     jmp 0xc2    ; 0xc2 <_exit>

...

000000a4 <main>:
  a4:   80 e2           ldi r24, 0x20   ; 32
  a6:   84 b9           out 0x04, r24   ; 4
  a8:   f8 94           cli
  aa:   8f ef           ldi r24, 0xFF   ; 255
  ac:   87 bd           out 0x27, r24   ; 39
  ae:   82 e0           ldi r24, 0x02   ; 2
  b0:   80 93 6e 00     sts 0x006E, r24
  b4:   84 bd           out 0x24, r24   ; 36
  b6:   78 94           sei
  b8:   85 e0           ldi r24, 0x05   ; 5
  ba:   85 bd           out 0x25, r24   ; 37
  bc:   80 e0           ldi r24, 0x00   ; 0
  be:   90 e0           ldi r25, 0x00   ; 0
  c0:   08 95           ret

000000c2 <_exit>:
  c2:   f8 94           cli

000000c4 <__stop_program>:
  c4:   ff cf           rjmp    .-2         ; 0xc4 <__stop_program>

You can see at address 0x74 it calls main, and then jumps to exit. exit turns off interrupts.
With interrupts off your ISR will not toggle pin 13.


text:
Interrupt for traffic light
I have mini project which is Emergency Traffic Light for Ambulance, police etc.
What I am try to do is when emergency traffic light go through first sensor 1 (in this code I just using button, “SA”), traffic light will be pause and the traffic light for ambulance will be green.
After ambulance go through second sensor (SB), traffic light will be reset and the flow become normal (red → orange → green).
My problem is I don’t know how to make interrupt for this code.
I hope anyone can help me.

#define SA 2 //sensor 1
#define SB 3 //sensor 2
#define IND 6 //indicator
/////////////////////////////////////
#define AH 13   // A
#define AK 12
#define AM 11
/////////////////////////////////////////
#define CH 10    //C B
#define CK 9
#define CM 8
#define yellowBlinkTime 500 // 0.5 seconds for yellow light blink

///////////////////////////////////c
#define BH A0   // B
#define BK A1
#define BM A2
///////////////////////////////////////////////

boolean TA = true; // west = true, east = false
int flowTime = 10000; // amount of time to let traffic flow
int changeDelay = 2000; // amount of time between color changes

void setup()
{
pinMode(SA, INPUT); //sensor 1
pinMode(SB, INPUT); //sensor 2
pinMode(IND, OUTPUT);   //indicator

pinMode(AH, OUTPUT);   // A
pinMode(AK, OUTPUT);
pinMode(AM, OUTPUT);
///
pinMode(CH, OUTPUT);   //C
pinMode(CK, OUTPUT);
pinMode(CM, OUTPUT);
///////
pinMode(BH, OUTPUT);   // B
pinMode(BK, OUTPUT);
pinMode(BM, OUTPUT);

// set initial state for lights -
//jalan A
digitalWrite(AM, LOW);
digitalWrite(AK, LOW);
digitalWrite(AH, HIGH);

//jalan C
digitalWrite(CM, HIGH);
digitalWrite(CK, LOW);
digitalWrite(CH, LOW);

///// JAlAN B
digitalWrite(BM, HIGH);
digitalWrite(BK, LOW);
digitalWrite(BH, LOW);

}//-------setup end

void loop()
{
  if(digitalRead(SA) == HIGH )
  {
  blink();
  //flow();
  //break;
  }

  else{

  flow(); // p void flow normal
} // end else
} // end void loop

void flow() // flow normal tf
{
//flow1
digitalWrite(AK, LOW);
digitalWrite(AM, LOW);
digitalWrite(CK, LOW);
digitalWrite(AH, HIGH);
digitalWrite(CM, HIGH);

digitalWrite(BH, LOW);
digitalWrite(BK, LOW);
digitalWrite(BM, HIGH);

delay(changeDelay);

//flow2
digitalWrite(AH, LOW);
digitalWrite(AM, LOW);
digitalWrite(AK, HIGH);

digitalWrite(CM, HIGH);

digitalWrite(BM, HIGH);
delay(changeDelay);

//flow3
digitalWrite(AK, LOW);
digitalWrite(CM, LOW);
digitalWrite(AM, HIGH);
digitalWrite(CH, HIGH);
digitalWrite(BM, HIGH);
delay(changeDelay);

//flow4
digitalWrite(AK, LOW);
digitalWrite(AH, LOW);
digitalWrite(CM, LOW);
digitalWrite(CH, LOW);
digitalWrite(AM, HIGH);
digitalWrite(CK, HIGH);
digitalWrite(BM, HIGH);
delay(changeDelay);

//flow 5
digitalWrite(AK, LOW);
digitalWrite(AH, LOW);
digitalWrite(AM, HIGH);
digitalWrite(BH, HIGH);
digitalWrite(BM, LOW);
digitalWrite(CK, LOW);
digitalWrite(CH, LOW);
digitalWrite(CM, HIGH);
delay(changeDelay);

//flow 6
digitalWrite(AK, LOW);
digitalWrite(AH, LOW);
digitalWrite(AM, HIGH);

digitalWrite(BK, HIGH);
digitalWrite(BH, LOW);

digitalWrite(CM, HIGH);
digitalWrite(CK, LOW);
digitalWrite(CH, LOW);

delay(changeDelay);

}//-------flow end

void blink()
{
[enter link description here][2]
    digitalWrite(AH, LOW);
    digitalWrite(AM, LOW);

    digitalWrite(BH, LOW);
    digitalWrite(BM, LOW);

    digitalWrite(CH, LOW);
    digitalWrite(CM, LOW);

    digitalWrite(AK, LOW);
    digitalWrite(CK, LOW);
    digitalWrite(BK, LOW);
    delay(yellowBlinkTime);

    ////////////////////////////////////////////////// BLINK BLINK
    digitalWrite(AK, HIGH);
    digitalWrite(CK, HIGH);
    digitalWrite(BK, HIGH);
    delay(yellowBlinkTime);

}  ///////////////// end void blink

Try using millis() instead of delay(). delay() literally delays the code, thus stopping it from doing it anything else. The loop simply pauses at the delay for the desired amount of time: thus nothing else can be done. millis() does not do this. Instead, it continuously reads out time, compares it to an earlier measurement to see how much time has passed. You can then program what it should do when it crosses a specific threshold (i.e. 20 seconds). You can find tutorials on millis() on the Arduino website.

I can truly advice you to use millis() from now on, instead of delay() as it will make your code much more efficient. Especially with semi-complicated stuff like this.

Also you should look at using a Finite State Machine instead of linear code like that.

The use of two letter variable and constants names make the code RF difficult to read.  You could look at using functions to perform repetitive tasks and reduce the volume of code.  Using delay statements like this is locking up your code, also it means that your timing will drift particularly if you service an interrupt, try triggering state changes at a certain time, this will also let you monitor sensors without interrupts.

monitor pin changes with https://github.com/neu-rah/PCINT , still you have cycle your code to allow changes, do not use delay and do not do all work inside interrupt handlers (it wont work) instead use them to set a flag and allow your code to react to that flag change quickly (therefor do not use delay)

You probably do not need to use interrupts. A typical Arduino's clock runs at 16MHz. A rough calculation means that you will be getting well over 5 million instructions per second. So unless you are doing some extremely intensive other processing and/or your ambulance is travelling near the speed of sound, polling the sensors should be fast enough. Next consider finite state machines as suggested above to simplify your code. Oh yes, don't use delay - if you do, you are simply throwing away the millions of instructions per second available for you to use.


text:
Can I power my Arduino Uno with a 9V / 990mAh battery?
I have a 9V Lion 990mAh battery. I am not sure if I can use it to power an Arduino externally?
Can you please guide me how to understand current specifications of any device?
Thanks and Regards,
Manish

While this answer addresses the specific question it should also prove useful as a link to resources relating to current reduction in other microcontroller projects.
Short:
The "C" rate for a cell is a current in mA numerically equal to the capacity in mAh
eg 1000 mA for a 1000 mAh cell.
In the absence of a specific data sheet a LiIon or LiPo cell is probably safe for maximum charge and discharge rates of C/2 and C.
ie 500 mA max charge rate for a 1000 mAh cell and
1000 mAh max discharge rate for a 1000 mAh cell.
In many cases double those rates will be safe.
Charge rates are seldom higher than C but discharge rates of substantially higher than 2C MAY be safe - see data sheet!.
In your example case, the operating time will be approximately mAh/average_current. Consult the data sheet for your microcontroller and/or measure current drain.
A typical "bare" Arduino with processor, USB IC, LEDs and "glue" components probably draws typically 50 mA and maybe up to 100 mA. Adding external loads can increase this - depending entirely on the load.
At say 100 mA average drain you'd get approximately 900/100= 9 hours operation. Running just the processor and on board components / peripherals you'd probabaly get twice times as long. By targeting low current methods (see refs ate end) you could get MUCH longer.

Most LiIon batteries are rated to charge at up to the "C" rate - ie 990 mA for a 990 mAh battery and to safely discharge at several times as much. Some manufacturers rate their batteries for lower maximum charge rates and this also can vary with the intended cell application. A "high energy" cell is liable to have lower charge and discharge rates than a "high power" cell. This relates to means of construction and to be safe the manufacturer's data sheet should be consulted.
The battery "capacity" rises somewhat as rates decrease below 'C' and fall significantly for rates above C.
Here is an excellent example data sheet for selected Sanyo LiIon cells . These are only examples but give a reasonable idea of what can be expected from a reasonable quality product.

Arduino per pin current limitations
Typical current draw](http://gadgetmakersblog.com/arduino-power-consumption/)
Excellent - Methods of reducing Arduino power consumption  & Related & more
Stack exchange discussion - How much current do you require in Arduino and embedded systems projects?


text:
HLK-RM04 wifi shield factory reset?
I have this HLK-RM04:

It came with  no catalogue or manual
all threads about it are in Chinese
after when I found the configuration webpage and changing it to client
it wont connect and it stopped board casting hlink wifi
how could i reset to factory settings?
After very long search I found an English manual.

What does Trst means ?
I don’t understand what I must do to reset it!

Since no one has posted an answer, and I finally found one myself. Ground pin 10 for 6 seconds.


text:
Trouble with setting the PWM frequency for Arduino Due
I'm using Arduino Due and I set the analog read and write resolution to 12-bit for better resolution. Basically all I do is to vary PWM duty cycle by controlling analog DC input voltage from 0 to 3.3V. The simple code as it is now works fine as follows:

int pwmPin9 = 9;
int analogPin0 = 0;
int val = 0;

void setup() {

  Serial.begin(9600);

  pinMode(pwmPin9, OUTPUT);  // sets the pin as output
  analogWriteResolution(12);
  analogReadResolution(12);

}

void loop() {

  val = analogRead(analogPin0);  // read the input pin
  Serial.println(val);
  analogWrite(pwmPin9, val);

}

My problem is I need to set the frequency of the PWM output to 25kHz or at least something nearest above 25kHz.
I have been searching forums hours and couldn't find any solution. Here I came across a way but there is no library called variant.h in my folders. And that code if I include in my script doesn't change anything.
What could be a workaround for this?
(I used to achieve this via this site by using Arduino Uno but for Due couldn't find any working solution)
Edit: I found the file and made the following change in variant.h:
 * PWM
 */
#define PWM_INTERFACE       PWM
#define PWM_INTERFACE_ID    ID_PWM
#define PWM_FREQUENCY       20000
#define PWM_MAX_DUTY_CYCLE  4095
#define PWM_MIN_DUTY_CYCLE  0
#define PWM_RESOLUTION      12

/*
 * TC
 */
#define TC_INTERFACE        TC0
#define TC_INTERFACE_ID     ID_TC0
#define TC_FREQUENCY        20000
#define TC_MAX_DUTY_CYCLE   255
#define TC_MIN_DUTY_CYCLE   0
#define TC_RESOLUTION       8

But it only works for 20kHz. If I set to 25kHz or 30kHz I don't get any error but also don't get any output :((

There are a few things to do. I've used this successfully in the past with older projects.
As a side note one can very easily change PWM settings on pins with the esp32, a single line of code being ledcSetup(PWM_Channel_Number, Frequency, resolution) without ever having to actually dive into modifying variant.h
To Quote Kerry D. Wong:

If you take a look at the function PWMC_ConfigureClocks in pwmc.c, you will see that the highest PWM frequency can be accommodated as the function input is 42 MHz, this is because inside the function it calls FindClockConfiguration which in turn ensures that the frequency parameter passed in is less than the MCK frequency. Thus for integer dividers, the highest frequency we can pass in is 42 MHz (with divider 2).
To achieve the highest output frequency, we can use a one bit PWM which essentially just outputs a square wave with a duty cycle of one. We can then set the prescaler to 2 to obtain an 84 MHz waveform.

#include <Arduino.h>

uint32_t pwmPin = 8;
uint32_t maxDutyCount = 2;
uint32_t clkAFreq = 42000000ul;
uint32_t pwmFreq = 42000000ul;

void setup() {
  pmc_enable_periph_clk(PWM_INTERFACE_ID);
  PWMC_ConfigureClocks(clkAFreq, 0, VARIANT_MCK);

  PIO_Configure(
    g_APinDescription[pwmPin].pPort,
    g_APinDescription[pwmPin].ulPinType,
    g_APinDescription[pwmPin].ulPin,
    g_APinDescription[pwmPin].ulPinConfiguration);

  uint32_t channel = g_APinDescription[pwmPin].ulPWMChannel;
  PWMC_ConfigureChannel(PWM_INTERFACE, channel , pwmFreq, 0, 0);
  PWMC_SetPeriod(PWM_INTERFACE, channel, maxDutyCount);
  PWMC_EnableChannel(PWM_INTERFACE, channel);
  PWMC_SetDutyCycle(PWM_INTERFACE, channel, 1);

  pmc_mck_set_prescaler(2);
}

void loop()
{

Note that VARIANT_MCK is defined in /arduino-1.5.7/hardware/arduino/sam/variants/arduino_due_x/variant.h as 84000000. PWM_INTERFACE_ID and PWM_INTERFACE are defined in variant.h as ID_PWM and PWM which in turn are defined in /arduino-1.5.7/hardware/arduino/sam/system/CMSIS/Device/ATMEL/sam3xa/include/sam3x8e.h.
So as the conclusion, the highest stable frequency we can generate using an Arduino Due is 84 MHz. The pictures below show the captured waveforms under different frequencies. For the 21 MHz waveform, pwmFreq is set to 21000000, no prescaler is used. For the 42 Mhz waveform, pwmFreq is set to 420000 with no prescaler. The 84 MHz waveform is generated with set to 42000000 and the prescaler set to 2.

Hope this helps.

Did you read what I was asking? My question is "But it only works for 20kHz. If I set to 25kHz or 30kHz I don't get any error but also don't get any output :(( " This does not set to PWM freq, to 25kHz.

Yes, but following the methods i said, should allow you to achieve the pwm setting you want...does it not do so? Can you set to any other freq above the khz range? Or does it just fall apart at anything above 25khz?

No that doesnt work. And your answer is not an answer at all. Im looking for a solution not advice. This is bounty question. Please delete your answer otherwise I will have to delete this question. You are not even using Due but attempting to answer such a technical specific question about it.

If you want a solution to ‘why doesnt the technical solution work with my hardware that i have no errors except it doesnt work to help with trouble shooting’ then you should delete this question, and re ask with useful information than ‘it doesnt work!!!!!’ :)

@user16307, you can wait for another answer. if you delete the question, you loose the bounty points. this answer will not get bounty points without at least two upvotes.


text:
How to fix baud rate when hardware capacity has a low limit?
I have a transmitter(simple 433 MHz transmitter) connected via digital pins on the Arduino. The receiver is connected to another arduino.
Now, I kept that pin on HIGH for 1 second, and it transmits only 1000 ones.
But I've seen different example transmitter sketches having baud rates of 1200, 9600, etc.
So the situation is, when the transmitter is transmitting at maximum capacity(just HIGH for a whole second), it can only transmit 1000 ones.
I am able to read that it only transmits 1000 ones because my receiver just has a simple read function that reads and prints the data. and it prints 1000 ones every second. Give or take one or two.
So when you specify a baud rate of 1200, is it useless? how will it transmit 1200 bits/sec?
Does the baud rate actually increase the hardware limit or what exactly is going on? Can someone please provide me some insight into this? I'd be glad to clarify this question more if need be.

Yes, please clarify. I have no idea what you're asking.

I made an edit.

Perhaps it would help if you mentioned what sort of "transmitter" you're talking about.

I suspect this is related to the OP's other post about serial transmission. it can only transmit 1000 ones - how do you get that? If it is high for a second, you could argue it has transmitted a billion ones. So when you specify a baud rate of 1200, is it useless? - no. You might want to read my post about how serial works.

Hey Gammon, I'm looking at your forum rn. Thank you! I'll really look into this.

I have a transmitter(simple 433 MHz transmitter) - please specify the model of the transmitter (part number). Also are you transmitting to another Arduino, or some other device which has a known protocol?

The transmitter you're using is very basic, and only transmits "on" and "off". As such it is protocol-agnostic. In order to use it effectively we use it with a protocol that uses "on" and "off" as its signalling, but also includes framing information so that we can know when the data flow starts and stops.
One such protocol is the UART protocol consisting of 1 start bit, 5 to 9 data bits, an even, odd, or no parity bit, and 1, 1.5, or 2 stop bits, all being generated at a specific rate. This rate is the "baud rate", and must match in both the sending device's and the receiving device's UART in order for them to communicate. This is true whether the devices are connected by a wire, an optical link, or a radio link.
The TX and RX pins on an Arduino are connected to a hardware UART which will handle the framing and signal generation for you. The hardware UART(s) can be accessed via Serial on non-USB-native Arduinos as well as Serial1, Serial2, and Serial3 on Arduinos where they are present.
Additionally, SoftwareSerial can be used to generate a UART signal on arbitrary pins in software, but you're almost always better off using a hardware UART when possible.

Hello Gammon, I'm looking into all the things you just talked about. I also have a request. I don't have enough rep points to do so, but I would like to create a new tag called Voice Over IP (VOIP). It's a very common topic in the wireless communication world, and stackoverflow doesn't have that tag yet. So may you please create it? Thank you!


text:
How to transmit more than 1 byte continually?
In software serial, the write function only sends 1 byte at a time. Is there someway, some library, that i can send multiple bits/bytes, without stopping (and not using digitalWrite)? i want to be able to transmit at least 16 bits as opposed to just 8.
I know i can send 2 bytes, or even 100 bytes. But the thing i'm trying to do is, implement my own LDPC(error correction) codes on the Arduino. Therefore, i'm taking a lot of channel measurements. One of them is figuring out how the error happens during the delay between the stop bit and the next startbit. Often times, this is were synchronization problems occur. So I'm trying to track this down. Hence why, I need to send more than 8 continuous bits. In software serial, it transmits 8 bits, then transmits the stop bit. then write() restarts on the next call. Instead of this, i just want to send more bits, like 64 bits for instance, and look at the BLER on the received data. (the reason why I'm staying away from hardware serial is because i'm doing this with wireless RF modules) Do you guys have any further info regarding this? I'm very grateful! Thank you so much!
Also, it was suggested that I write my own softwareserial, but that's a pretty daunting task. I would like to avoid it, if i can.
EDIT: Let me show you my data.
So, I'm constantly transmitting the values; 123,124,125,126.
1111011
1111100
1111101
1111110

The above 4 lines repeat about 2 times. Then, suddenly, it synchronizes incorrectly, and the following 4 lines are being constantly repeated.
11110101
11111001
11101101
11110001

It never syncs back to the original 4 transmissions. Now, inside the unsynced block of 4 transmitted bytes, there are fragments of the correct transmission inside. For instance, start from the 2nd bit of the 3rd byte of the correct transmitted byte. Now, if you account for the '0' start bit, and try to matchup the bits, the correct bits are being picked up in the correct order. It's just a problem of what the receiver takes as the startbit.
As i'm typing this edit, i realized something else. What i said in the above paragraph is true, then for the unsynced block, there should be a '0' start bit in front. Now, if the messages match up exactly, and if the 0 start bit that is being transmitted is being treated as a payload, then which 0 is being treated as the startbit, because all the bits between the synced and unsynced data are matched up. However, there should be one missing 0 each time because it's being read as a startbit, not databit.
Sorry if this is convoluted. Happy to clarify any part of it. Thank you so much!!

Is it possible to just go into my write function, and just change the loop from iterating 8 times to 32, and then make the parameter take in 32, and do the according changes just in that function? I'm 99% sure changing software serial isn't that simple and that other parts of the code would be affected, but worth a shot.

figuring out how the error happens during the delay between the stop bit and the next startbit - there can be any time between the stop bit and the next start bit.

@NickGammon Hello sir, can you please take a look at my edits? thank you so much!

How much gap (in time) do have between blocks of data?

I've tried both ways. Having no delay and having some delay. With a delay, it works fine. However, my question is how the synchronization can happen the way it is. Because the right data is being shifted and I am able to do a perfect one to one mapping of how it was shifted, however, because the data being read is starting at a different point, there should be one missing 0 that's being treated as a start bit. @NickGammon

With no delay on the sending end, a slight pause at the receiving end means it misses the start bit. Then the next zero to come along appears to be the start bit, and you get the bit shifting you talk about. A small delay is probably very advisable.

Yes, the next zero to come along should be the start bit. However, that 0 is not missing. Because the startbit shouldn't be printed, but i don't see any missing zeros in the 2nd (unsynced) data. Also, I'm using the same "read without block" that we discussed in a previous post. I'm not sure if I'm being clear. So there is an exact mapping from the actual data to the unsynced one. However, when it becomes unsyncde, some new 0 bit should be treated as the startbit, in which case it should not be printed. But i don't see any misisng zero. It's as if the actual data just got shifted.  @NickGammon

I want to point out here that async serial communications relies on both ends providing a clock (there is no transmitted clock signal). Thus the sender clocks out bits at the "baud rate" (eg. 9600 bits per second) and the receiver clocks them in at the same rate.
With a start bit and 8 data bits therefore you can tolerate some difference in the clocks between sender and receiver (and there will be some difference). Effectively you could probably tolerate around a 10% difference in clock frequencies, as even if they are out by 10% the sample at the receiver will still land inside the data bit of the sender.
Now if you want to transmit 64 bits you have reduced this error margin by a factor of 8. So let's say (ball park) that you can now only tolerate a difference of 1% between sender and receiver.
You now need to be pretty sure that the clocks on the respective boards are pretty accurate. The Uno, for example, has a resonator CSTCE16M0V53-R0 which appears to have a tolerance of 0.5% and a frequency stability of 0.2%.
So, if the sender is running 0.5% slow, and the receiver 0.5% fast, you will almost certainly get errors.

However, when it becomes unsyncde, some new 0 bit should be treated as the startbit, in which case it should not be printed. But i don't see any misisng zero. It's as if the actual data just got shifted.

How will it get unsynced?  I don't think you are following how serial comms works. If you don't have any delay between bytes (or batches of bytes in your case) then it is impossible to resync, because if you miss a start bit, all the following bits will appear valid, they'll just be shifted. This is exactly what you are describing.
Really, to ensure syncing you need to have a gap between bytes (or batches-of-bytes in your case) longer than a byte might be, otherwise you can get this mis-sync happening. So if you make your batches longer, the gap has to be longer, effectively removing the slight advantage of larger batches.
Imagine you have an incoming stream of bits on the receiver:
011110101101100011110101101101101100110101100101100110101111001010101110111001010101111
1101001010100101101001010100111011111001000010111100100011011001001001001011001001010

And imagine that you missed that first start bit. Without a gap between bytes (which would appear as: 111111111) you have no way of knowing which is a start bit and which is a data bit. Valid data would have a start bit, so you don't mistake valid data for the inter-byte gap.
In other words, with 8-bit bytes, data will always be 0xxxxxxxx1 and thus a gap of 1111111111 must be the gap and not data because there is no zero there. But with any shorter gap, and if the receiver samples in the middle of byte, it certainly might think that the next 0 in the stream is a start bit (wrongly).

The question concerns transmission via radio, so serial clock differences are probably not the source of error.  Rather the poster is investigating channel noise.

@NickGammon,  hey, I've made some edits to the question to show exactly what's happening. Thank you so much for all your help, once again.

@ChrisStratton, Hey, yes, I am investigating channel noise, but it seems that the mis-synchronization ultimately does give me incorrect data as well. My goal, however, IS to analyze channel noise and implement optimal error correction code. But i'm trying to get past this incorrect synchronization problem first.

Unless you have bad crystals or diverse implementation with badly approximate divider ratios, it is relatively unlikely that there is an actual "synchronization problem" behind what you are seeing.  Rather, you are probably seeing noise in the radio channel, possibly noise which is interfering with the detection of synchronization or clock recovery.


text:
hello,i have an problem with my arduino with an lcd
i've totally done everything i could,but when i run my arduino uno with my 16*2 lcd (with i2c) . it has a higher brightness on the top and a lower one in the bottom. ive even tried putting example codes but my arduino totally freaks out, starting to change it's backlight . i cant even use lcd.print . i had tried just to adjust my lcd with a ldr , this is the code:
    // Include Wire Library for I2C
#include <Wire.h>
// Include NewLiquidCrystal Library for I2C
#include <LiquidCrystal_I2C.h>
int ldr;
int sensor=0;
int lcdb=5;

// Define LCD pinout
const int  en = 2, rw = 1, rs = 0, d4 = 4, d5 = 5, d6 = 6, d7 = 7, bl = 3;

// Define I2C Address - change if reqiuired
const int i2c_addr = 0x3F;

LiquidCrystal_I2C lcd(i2c_addr, en, rw, rs, d4, d5, d6, d7, bl, POSITIVE);

void setup()
{

  // Set display type as 16 char, 2 rows
  lcd.begin(16,2);
  Serial.begin(9600);
  lcd.setCursor(0,1);
  lcd.print("hello world");
  lcd.setCursor(0,0);
  delay(1000);
  lcd.print("hello world");

}
void loop()
{
  int ldr=analogRead(sensor);
  ldr=map(ldr, 0, 1023, 0,255);
  delay(1000);
  analogWrite(lcdb,ldr);

}

Please also provide a wiring diagram, so that we can see, how everything is connected

What library are you using, because LiquidCrystal_I2C lcd(i2c_addr, en, rw, rs, d4, d5, d6, d7, bl, POSITIVE); doesn't make sense for the library I found. Also the code seems to imply the backlight is connected to pin 3 on the I2C device, but also to pin 5 of the UNO.

i used the new liquidcrystal library


text:
can ModbusRtu.h library send data from slave to master using modbus(RS485) module?
i am using ModbusRtu.h library for modbus protocol. it works for sending data from master to  slave but it can not send data from slave to master.
master code:
#include <ModbusRtu.h>
  #define SERIAL_BUFFER_SIZE 64
// data array for modbus network sharing
uint16_t au16data[26];
uint8_t u8state;

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  port : serial port
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus master(0,Serial1,8); // this is master and RS-232 or USB-FTDI

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram;

unsigned long u32wait;

void setup() {
  Serial1.begin( 19200 ); // baud-rate at 19200
  Serial.begin( 19200 ); // baud-rate at 19200
//  master.start();
 master.begin();
  master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
  u32wait = millis() + 1000;
  u8state = 0;
}

void loop() {

    telegram.u8id = 2; // slave address
    telegram.u8fct = 3 ; // function code (this one is registers read)3
    telegram.u16RegAdd = 0; // start address in slave 1     slave array index 0 dhora
    telegram.u16CoilsNo = 2; // number of elements (coils or registers) to read 4  //master array er koyta(not start from 0) value show korba
    telegram.au16reg = au16data; // pointer to a memory array in the Arduino
    int x = master.poll(); // check incoming messages
    Serial.print("x: ");
    Serial.println(x);
                if (master.getState() == COM_IDLE)
                {
                   master.query( telegram ); // send query (only once)

                }
Serial.print("Recieve: ");
      for (int i = 0; i < 5; i += 1)
      {
        Serial.print(au16data[i]);
        Serial.print(",");
      }
      Serial.println("");
}

slave code:
#include <ModbusRtu.h>
#define SERIAL_BUFFER_SIZE 64
// data array for modbus network sharing
//uint16_t au16data[26] = {
//  3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1 };
uint16_t au16data[26] = {4,17,89};
int led = 13;
/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  port : serial port
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus slave(2,Serial1,8); // this is slave @1 and RS-232 or USB-FTDI

void setup() {
  Serial1.begin( 19200 ); // baud-rate at 19200
  Serial.begin( 19200 ); // baud-rate at 19200
  pinMode(led, OUTPUT);
  slave.begin();
  //slave.start();
}

void loop() {

  slave.poll( au16data, 26 );

   Serial.print("Recieve: ");
      for (int i = 0; i < 5; i += 1)
      {
        Serial.print(au16data[i]);
        Serial.print(",");
        if(au16data[3] == 1)
        {
          digitalWrite(led, HIGH);
         // Serial.println("in");
        }
         if(au16data[3] == 2)
        {
           digitalWrite(led, LOW);
           //Serial.println("else");
        }
      }
         Serial.println("");

       memset(au16data, 0, 26 * sizeof(uint16_t)); // recieveLargeArray = {}
}

and which one of the many ModbusRTU libraries do you use?

i used this library https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino/find/master


text:
Arduino extended database library data type. Is char str[] in Arduino the equivalent of VARCHAR in SQL?
I am new to Arduino and I am currently working with an Arduino Uno and SD card module - SD/MMC for database storage using the Arduino database library from https://github.com/jwhiddon/EDB.
My question is, is the char str[] type the equivalent of VARCHAR?
Here is my arbitrary record definition for my table:
struct LogEvent {
  int logId;
  int unumber;
  char username[10];
  char fname[15];
  char lname[15];
  char role[6];
  char boxid[10];
  char userStatus[2];
} logEvent;

What's VARCHAR? Where is the definition of that? Are you referring to the SQL type?

I am referring to SQL type

You are asking if a SQL data type VARCHAR is "equivalent" to char str[]? What do you mean by the word "equivalent"? For one thing, SQL VARCHAR has a size associated with it: VARCHAR(size). So no, they are not equivalent.

If you mean, are these equivalent:
foo VARCHAR(100);

and:
char foo [100];

No, they are not equivalent, really. In the case of SQL you can put 100 characters into foo. In the case of C++ you would (generally speaking) put up to 99 characters into foo, with the final character being 0x00 which indicates the length of the string.
You could conceivably put 100 characters into foo but then you would have to store the size of foo in another variable.

If you're referring to the SQL type VARCHAR, then, vaguely. char username[10]; for instance will define a char array of 10 bytes. A char being the equivalent of a byte. That's about it for the type. This is C++, so you're pretty close to the iron, and a char array is about as basic as it gets. No collation, no encoding (remember that a character is not always a single byte!), no indexing. Just a bunch of bytes put together.