text:
Arduino Unreliable Serial communication
After reading the following 2 articles:
https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/
https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/
I have get rid of the complete String class from my main program and went back to using character arrays.
This seems to work reliably until some extent but once I start stress testing it, quickly turns out that it is not reliable at all!
Here is the complete code, you can load it into the mega and it will produce the same results (I have removed all other unnecessary parts from the code):
#define DEBUG

char Command_PC[64], Command_Xbee[64], Command[64];
int count=0;
bool Complete_PC=false;
bool Complete_Xbee=false;

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

} // END void setup

void comm() {

/* COMM FROM PC */
if (Serial.available()){

  #ifdef DEBUG
    Serial.println("PC: New command, collecting...");
  #endif
    count = 0;
    memset(Command_PC, 0, sizeof(Command_PC));
    while (Serial.available()){
      char character = Serial.read();
      if (character=='\n')
         {
          Complete_PC =true;
          break;
         }
      Command_PC[count] = character;
      count++;
    }
  }

/* COMM FROM Xbee */
if (Serial1.available()){
  #ifdef DEBUG
    Serial.println("Xbee: New command, collecting...");
  #endif
    count = 0;
    memset(Command_Xbee, 0, sizeof(Command_Xbee));
    while (Serial1.available()){
      char character = Serial1.read();
      if (character=='\n')
         {
          Complete_Xbee =true;
          break;
         }
      Command_Xbee[count] = character;
      count++;
    }
  }

   delay(500);

 if (Complete_Xbee || Complete_PC) {

  if(Complete_Xbee)
    strcpy(Command, Command_Xbee);
  else
    strcpy(Command, Command_PC);

  #ifdef DEBUG
    Serial.print("Command received: >");
    Serial.print(Command);
    Serial.println("<");
  #endif
           Complete_Xbee=false;
           Complete_PC=false;
 }

}

void loop()
{
    comm();

} // END void loop

The code is simple, all it is intended to do that whether there is a command coming from the PC (USB) or Xbee (attached to hardware uart) process it and do further things. As long as you typing in commands manually it goes reliably for a while but even then after 10-15 commands it might screws up. The automated testing with:
for ((;;)); do echo HELLOWORLD > /dev/ttyACM0; done
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORL<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLDELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOORLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWOD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWOLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWOLD<
ERR_INVALIDCMD
PC: New command, collecting...
Command received: >HELLOWLD<
ERR_INVALIDCMD
PC: New command, collecting...

Brings out the bug right away. Is there any problem with this code? Any ideas how to make this 100% reliable even if it takes slowing the main program down?
I have noticed that by adding: delay(500); it makes it more stable. If this is not there it will even fail on the first manually entered command like:
PC: New command, collecting...
PC: New command, collecting...
PC: New command, collecting...
Command received: >lloworld<

By adding a delay to my test script:
for ((;;)); do echo HELLOWORLD > /dev/ttyACM0 && sleep 1; done
It runs stable for a while but after 15 mins testing it start misbehaving again:
Command received: >HELLOWORLD<
PC: New command, collecting...
Command received: >HELLOWORLD<
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><

As @Edesign has mentioned your reception methodology is slightly flawed.  A better arrangement would be:
static int Count_PC = 0;
static bool Complete_PC = false;

if (Serial.available()) {
  char character = Serial.read();
  if (character=='\n') {
    Complete_PC =true;
    Count_PC = 0;
  } else {
    if (Count_PC < 62) { // Don't overflow the array...!
      Command_PC[Count_PC++] = character;
      Command_PC[Count_PC] = 0;
    }
  }
}

The count and complete flags are now static - that is, they retain their values between iterations of the loop. You only look at one character per iteration of the loop (you could enhance it by changing the first if to a while if you like, but this way plays better with handling multiple data sources), and add that to the string. Only when the \n is received do you flag it as complete. There is no clearing of the whole array, it's not needed - just ensure that you always add a \0 to the end of the string each time you add a character.
The current character position (Count_PC) is reset when you receive the \n so that it is ready to receive the next command - be sure that you process the command that same loop (which you do anyway).

I have tested this code and it comes up with about the same results. Running or ((;;)); do echo HELLOWORLD > /dev/ttyACM0 && sleep 1; done will produce ommand received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
PC: New command, collecting...
PC: New command, collecting...
Command received: ><
empty commands after about 10 mins. If I then stop the stress test for a second then restart it then it is working again for a while.

Also with your code if my delay(500); is not present then it returns empty right away for the word hello instead of receiving at least a couple of characters like ello.

You will have to show how you have fed this code into your existing code - how you handle the command and reset things will also have a bearing on things. As well as when you are doing your debug printing...

http://pastebin.ca/3737758 the difference is I still kept my while loop, breaking not breaking at \n made no difference during the tests however I believe that if I don't have the break statement there it is more stable, because if the end of the line is reached and there would be some junk characters after it in the buffer those would be erased by the Serial.read() and would not end up in my final Command_PC of course.

@Edesign: http://pastebin.ca/3737759 It is the complete code, I take out the xbee part because it's just a copy cat and not relevant for my testing here. No I left the if there and it does work as it did so far. After a while it becomes unreliable, I will test it with another arduino pro micro at the afternoon.

@Edesign, @Majenko: thank you for your help, it turns out that the hardware DOES matter as well. It was partially a hardware issue. Regarding my initial code, you can get that code remove the delay(500); from it and load it into an Arduino Leonardo and it will pass my first initial stress test without any delays and it works stable even after an hour testing.
I believe that both the Mega and the Leonardo have USB2 connections:
Bus 001 Device 003: ID 2341:0042 Arduino SA Mega 2560 R3 (CDC ACM)
Bus 003 Device 013: ID 2341:8036 Arduino SA
Although this is was a Keyestudio MEGA, a cheap chinese counterfeit which would explain why did it have this issue. My initial code was not wrong but as you have pointed out it could have been improved, what I did.
Code1:
static int Count_PC = 0;
static bool Complete_PC = false;

if (Serial.available()) {
  char character = Serial.read();
  if (character=='\n') {
    Complete_PC =true;
    Count_PC = 0;
  } else {
    if (Count_PC < 62) { // Don't overflow the array...!
      Command_PC[Count_PC++] = character;
      Command_PC[Count_PC] = 0;
    }
  }
}

Code2:
/* COMM FROM PC */
if (Serial.available()){

  #ifdef DEBUG
    Serial.println("PC: New command, collecting...");
  #endif
    memset(Command_PC, 0, sizeof(Command_PC));
    while (Serial.available()){
      char character = Serial.read();
      if (character=='\n')
         {
          Complete_PC =true;
          Count_PC = 0;
          //break;
         } else {
             if (Count_PC < 62) { // Don't overflow the array...!
                 Command_PC[Count_PC++] = character;
                 Command_PC[Count_PC] = 0;
             }
         }
  }
}

The difference between his code and my last code is that I do the while looping inside the function while his relies on the main loop cycles to complete the string.
Both are working but if the main program have a lot to do, his version will noticeably make the responses more sluggish. Which can be easily tested with:
 for ((;;)); do date > /dev/ttyACM0; done


text:
Arduino SSCANF stop on comma delimiter
I have the following problem, the arduino is receiving a command like
LCD,Display line text one, Display line text two
I use an strcmp to match the beginning of the string that works but now I would like to ignore the beginning of the string (LCD) and scan in the next 2 variables until the comma to 2 new variables.
                sscanf(Command, "%[^,]%[^,]%[^,]", &dummy, &lcd_display_l1, &lcd_display_l2);

I don't know if it's possible to ignore the first variable (which would be the LCD) but I setup a dummy variable for it anyway what I not going to use.
All I get with this is the LCD in the dummy the other 2 does not fill up.
I have tried this syntax:
https://support.microsoft.com/en-us/kb/38335
Doesn't work either. Any ideas?

Try "%*[^,],%[^,],%[^,]". The asterisk is for ignoring the field.

I would suggest using strtok() to chop the string up:
char *prefix = strtok(mystring, ",");
char *firstString = strtok(NULL, ",");
char *secondString = strtok(NULL, ",");

That has the effect of slicing the existing string up in memory replacing the commas with \0 and placing three pointers at the start of the three substrings. It has the advantage that it doesn't need to copy the contents of the string anywhere, so doesn't use any extra memory (other than the few bytes for the pointers).

source: Stack Exchange

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

sort: votes


text:
Arduino trim: does it remove the \n as well?
According to the manual:
https://www.arduino.cc/en/Reference/StringTrim
Trim strips one or more whitespaces from the beginning and the end. Does it also removes tabulators and \n ?
I have the following code which works:
 while (Serial.available()) {   // something came across the serial
      char c = (char)Serial.read();
      Command += c;
      Command.trim();
      if (c=='\n')
         {
           Complete =true;
         }
   if (Command.length() >0 && Complete) {

        if (Command == "LED_ON") {
               // Do stuff
        }

Although I'm not sure that it is working because of the last if statement which says: if (Command == "LED_ON") ignores the ending \n and say ok it matched OR Command.trim() really takes off that \n.
Thank you

OMG, he's using String! Argh! That's evil! I suggest you learn how to do things properly and don't rely on (broken) crutches like String. https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/ https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

I would make a general comment saying that similar functions in other programming languages that do 'trim' remove all whitespace which usually includes newlines spaces tabs carriage return etc etc. Its been confirmed that this version of trim does that but newlines and tab are generally considered whitespace in most languages.

Yes, \n is also removed.
The source for the trim() function is in WString.cpp.
void String::trim(void)
{
    if (!buffer || len == 0) return;
    char *begin = buffer;
    while (isspace(*begin)) begin++;
    char *end = buffer + len - 1;
    while (isspace(*end) && end >= begin) end--;
    len = end + 1 - begin;
    if (begin > buffer) memcpy(buffer, begin, len);
    buffer[len] = 0;
}

We can see it uses the isspace() function, but where's that function defined? WString.cpp only #includes WString.h, so we go there.
In WString.h, we can see it includes ctype.h. Time to go to the C++ Reference, which tells us that yes, \n is a "space" according to isspace(), so it is trimmed.
(note that isspace() is affected by localization settings. I'm not sure what the localization settings are when compiling for Arduino)

Whilst rchard2scout is quite right that trim will remove newlines, why not rearrange the code so it doesn't matter?
  char c = (char)Serial.read();
  if (c == '\n')
     Complete = true;
  else
     Command += c;

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

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


text:
Arduino Serial Response is Slow when in While Loop
Good evening all,
I'm having an issue with a quick "test" project that I am tinkering with (learning the "do's" and "don'ts") the NeoPixel LED strip.  I've been piecing together excerpts from other folks and so far everything is great.
I'm doing it over serial sending switch/case with numbers from the keyboard for different options.  The issue I am currently having is "case 1:", when I hit the "1" key and it fires off, I want to be able to interrupt it immediately by using key "0".  So basically, I'd like it to loop forever after hitting key "1" but terminate after hitting "0".
However, when hitting key "1", then key "0" immediately, the while loop repeats twice, then breaks.  I haven't done any C/C++ since I was 12 and now I'm 38 so now it is all trial and error based so please pardon my syntax.  Any help would be appreciated.
#include <Adafruit_NeoPixel.h>
#include <SoftwareSerial.h>

#define PIN 6
#define LEDs 16

int LED_Fade_Interval = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {

  Serial.begin(9600);

  strip.begin();
  strip.show();

}

void loop() {

  while (Serial.available() == 0);

  int numKey = Serial.read() - '0';

  uint32_t low = strip.Color(0, 0, 0);

  switch(numKey)
  {

    case 1:
      Serial.println("LED Strip is ON - BLUE FADE");
      while (numKey != 0)
      {
        int numKey = Serial.read() - '0';
        delay(50);

        ws2812_FadeInOut(0, 0, 255, LED_Fade_Interval);

        if (numKey == 0)
        {

          for( int i = 0; i<LEDs; i++){
            strip.setPixelColor(i, low);
            strip.show();
          }

          break;

        }

      }

    case 0:
      Serial.println("LED Strip is OFF");
      for( int i = 0; i<LEDs; i++){
          strip.setPixelColor(i, low);
          strip.show();
      }
      break;
   }
}

// *******************************************
// FADER Function
// *******************************************
void ws2812_FadeInOut(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip.show();
     delay(wait);
  };
};

What you are doing is a Scheduler. You can look for already made solutions like jm_Scheduler: https://git.io/v1L0a

NeoPixels' timing requirements are pretty tight - not necessarily high frequency but high accuracy, for at least certain parts of the serial pulse train. To achieve that, I believe the (Adafruit) NeoPixel library takes over one of the timers during the transmission and turns off interrupts for at least some of the time. That will have a negative impact on any background processes. Read through the NeoPixel library code; it should be clear.
However, while researching my answer (so as to not embarrass myself too badly!), I found this article at josh.com that describes driving NeoPixels with a much lower impact and goes on to demonstrate his technique with a video of a 1000 NeoPixel string(!) driven at 30 FPS by an old, apparently Atmega 168-based, Duemilanove.

Serial.read() reads one character from the Serial stream, or returns -1 if there are no characters to read.
When you send a 1 from the Serial Monitor, the Arduino board first receives an Ascii 1, and then receives a line-end character (eg, an LF from Linux) or characters (eg, a CR and LF from MSWindows).
Since none of 1, CR, or LF are equal to an Ascii 0, the numkey value computed at the fourth line of case 1 is not 0, so the exit condition isn't met.  Thus the fade loop continues running, until it sees a 0 character.
Instead of continuing to read characters within while loops within the switch/case statement, test if more serial input is available.  Note, avoid exiting early from case 1, after you read a digit at the beginning of loop(), read and discard the line-ending characters that follow.


text:
Can't connect to serial port
I'm trying to make my Arduino's LED blink for the first time, but when I try to upload the code I get the following error in the Serial Monitor:

Error opening serial port '/dev/ttyACM0'.
  Try consulting the documentation at http://playground.arduino.cc/Linux/All#Permission

BTW, I have serial.debug_rate=9600, so I don't think that's the problem. Can anyone help me with this please?

Did you consider following the provided link and trying the things it suggests?

You can also find more information and tips here: https://hackingmajenkoblog.wordpress.com/2016/08/24/diagnosing-arduino-problems-in-linux/

It seems your serial does not have the right permissions to be opened in user mode. Try adjusting that by typing
sudo chmod a+rw /dev/ttyACM0

on the console (open it by CTRLALTT).

That issue is due to your username not being in the dialout group.
Try: sudo usermod -a -G dialout yourusername and rebooting to load the changes, then check again if the problem still persists...
I wrote an article about that here: Solving Arduino IDE upload problem, and serial monitor error on Ubuntu.


text:
Emulate non-standard keyboard from Arduino
I want to emulate keyboard presses in an old C64 microcomputer using an Arduino.
The keyboard connection is a non-standard 20-pin port (i.e. the Arduino keyboard libraries won't be useful) which, as I understand, works as a simple matrix of switches.
Since my Arduino Mega has more than 20 general purpose I/O ports, I understand I can approach the problem by simply mapping these 20 keyboard pins to individual "digital" Arduino ports, and then programming around it, right?
Or is this too naive and I'm missing something here?
I'm new to Arduino, so any comments highly appreciated. Thank you!

Please provide more information about the keyboard for the C64 computer. Is there a link perhaps?

Thanks sa_leinad. Here is one: http://www.waitingforfriday.com/images/b/be/C64-12.png

Emulating a keyboard matrix is actually harder than you would at first think. It's not just a case of setting certain combinations of pins as HIGH or LOW - you need to actively monitor one side of the matrix as it sweeps across each row and control the other side depending on the buttons that are pressed or not pressed on the current row. And all that has to be done fast enough that the C64 doesn't see buttons constantly bouncing up and down.
Further, you really need all your outputs to be open drain so as not to interfere with each other or the rest of the system (depending on just how the C64 system works), and Arduinos can't do open drain natively - instead you have to emulate it by switching between INPUT and OUTPUT + LOW which adds extra latency.
If you only want access to a few of the buttons a better arrangement would be to add a small N-channel (logic level) MOSFET or an NPN BJT between the two sides of the matrix for whichever button(s) you want to control (check the schematics for which pins and which way round to connect it). Activating the transistor would then be the same as pushing the button down. It can even be in parallel to the existing button so as to not break the keyboard.

Thank you Majenko! I'll reconsider the project given your valuable input -- not giving up yet, but more reading up to do... And I want to emulate the entire keyboard (including possible key combinations, e.g. Ctrl + something).

The main concern you have with emulating a matrix is "what is the time between a row being activated and the column being read?" - If there is a good sized delay between the two then you could be in luck and it will be easy. If it's almost instantaneous then you could well have problems. You have to make sure that all the outputs are set right before that read is done. You may end up having to do it with a different system, such as a CPLD, in order to get the speed you need.

I would go for two 4051 connected by common line and multiplexed lines to rows / cols (as Commodore keyboard is 8x8 matrix)

I know this is out there but how about using the Arduino to drive relays to re-enact the key being pressed. Just a crazy idea.

KIIV, as far as I understand 4051 demultiplexing, in this arrangement I would not be able to simulate key combinations. It seems 4051 enables you to select 1 output at a given time. So with two 4051s (one for row, one for column) I would be able to simulate 'F3' and 'Ctrl' at a time, but not 'Ctrl + F3' simultaneously.


text:
How to connect a digital sensor through SPI
I want to connect a ADXL355 development board accelerometer to an Arduino. I cant get any data form the sensor. The data_ready pin is never high and I can't read the registers.
The connections (user guide):
I connected VDD and VDDIO to 5V, ground to ground, DRDY to the correct pin, CS, SCLK, MOSI and MISO all to correct pins.
Code:
//modeled on https://www.arduino.cc/en/Tutorial/BarometricPressureSensor

#include <SPI.h>

const int ID = 0x00;
const int FIFO = 0x11;
const byte READ = 0b11111100;
const byte WRITE = 0b00000010;

const int dataReadyPin = 6;
const int chipSelectPin = 7;

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

    // put your setup code here, to run once:
    SPI.begin();

    // initalize the  data ready and chip select pins:
    pinMode(dataReadyPin, INPUT);
    pinMode(chipSelectPin, OUTPUT);

    delay(100);
    readRegister(ID);
}

void loop() {
    if (digitalRead(dataReadyPin) == HIGH){
        Serial.println("data ready");
        delay(500);
    }
}
void readRegister (byte thisRegister){
    byte inByte = 0 ;
    Serial.println(thisRegister, BIN);

    thisRegister = thisRegister<< 2;
    byte dataToSend = thisRegister & READ;
    Serial.println(thisRegister, BIN);
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(dataToSend);
    inByte = SPI.transfer(0x00);
    Serial.println("data: ");
    Serial.println(inByte);
}

You're shifting your address too far.

Read should be 0b00000001 not 0b00000010.
Your address should be shifted one bit not two.

Also you need to turn it on. By default the device is in standby mode. You need to enable it by setting bit 0 of register 0x2D to 0.

byte readRegister (byte thisRegister){
    byte inByte = 0 ;
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer((thisRegister << 1) | 1);
    inByte = SPI.transfer(0x00);
    digitalWrite(chipSelectPin, HIGH);
    return inByte;
}

void writeRegister (byte thisRegister, byte value){
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(thisRegister << 1);
    SPI.transfer(value);
    digitalWrite(chipSelectPin, HIGH);
}

Thank you for your help. I thought it should be shifted by 2 because of the tutorial I am following... While debugging, I connected the ground pin on the 3-pin group labelled standby to ground, and it shorted out. What is the group for?

"Standby or Measurement Mode Selection Pin. Set this pin to ground to enter standby mode, or set this pin
to VDDIO to enter measurement mode. " - should do something similar to bit 0 of register 0x2d, but inverted.


text:
How to get data from a sensor's FIRST IN FIRST OUT FIFO register (from two's complement)
I want to get acceleration data from a ADXL355 sensor.

My code:
void readFIFO (){
long data[3];
byte data2 [9];

digitalWrite(chipSelectPin, LOW);
SPI.transfer( (FIFO<<1) | 1);
for (int i = 0 ; i < 9; i++){
    data2[i] = SPI.transfer(0x00);
}
digitalWrite(chipSelectPin, HIGH);

Serial.println("Byte data in hex and binary");
 for (int j = 0 ; j < 9 ; j++){
    Serial.print("element "+String(j) +": ");
     Serial.print(data2[j],HEX);
     Serial.print(" ");
     Serial.println(data2[j],BIN);
 }
 for (int z = 0 ; z < 3; z++){
    data[z] = ((data2[z*3]<<12) | (data2[z*3 +1] << 4) | (data2[z*3+2]  >>4));
 }
 Serial.println("concatenated values: ");
 for (int i = 0 ; i < 3 ; i++){
    Serial.println(data[i]);
 }
}

Sample output:
Byte data in hex and binary
element 0: F9 11111001
element 1: 1B 11011
element 2: 51 1010001
element 3: 0 0
element 4: FD 11111101
element 5: 90 10010000
element 6: C3 11000011
element 7: 2A 101010
element 8: 20 100000
concatenated values:
-28235
4057
12962

The values are two's complement. Are these the correct values? If not what am I doing wrong?

You need to sign extend the results.
e.g.
If the value is -1 your 3 byte values will be: 0xff ff f0
Combining these in to a single 32 bit value as you do gives you: 0x00 0f ff ff
Which is not -1.
What you need to do is check the most significant bit of the value and if it is set then set the top 12 bits.
for (int z = 0 ; z < 3; z++){
  data[z] = (((long)data2[z*3]<<12) | ((long)data2[z*3 +1] << 4) | (data2[z*3+2]  >>4));
  if (data2[z*3] & 0x80)
    data[z] |= 0xfff00000;
}

Since you've had no response to this I'll add my experiences with this chip. I'm not sure why you are reading the FIFO buffer. The chip provides three registers for each of the three axes. I simply read those in a loop. You can find my (still very crude) Python to read these at https://github.com/markrad/ADXL355. I hope it's some help to you.

FIFO buffers are extremely useful for IC's with an ADC so you can poll the sensor for the data less frequently and get all samples that were collected in the interim. This prevents you from having to have a very tight sampling loop if you have many sensors to communicate with.


text:
Is this a good function for I2C receive?
I'm trying to fix my I2C code:
Is the following function correct because it has multiple returns. I don't know if that would work.
uint8_t I2C_rx(uint8_t ack_rx)
{
    uint8_t i;
    if (ack_rx)
    {
        TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA); // sending ACK
        while (!(TWCR & (1<<TWINT)));
        return TWDR;
    }
    else
    {
        TWCR = (1<<TWINT)|(1<<TWEN);           // sending NACK
        while (!(TWCR & (1<<TWINT)));
        return TWDR;
    }
}

No problem with multiple returns but it could be reduced to:
uint8_t I2C_rx(bool ack_rx)
{
  uint8_t cr = (1<<TWINT) | (1<<TWEN);
  if (ack_rx) cr |= (1<<TWEA);
  TWCR = cr;
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

or
uint8_t I2C_rx(bool ack_rx)
{
  TWCR = (1<<TWINT) | (1<<TWEN) | (ack_rx<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

Cheers!


text:
Arduino as Slave to Return Multiple Values
I'm having trouble trying to get my two Arduino Unos to communicate with each other over i2c. I'm trying to have the master request for analog values from the slave by sending a request to the slave device for one of the six ADC pin values.
Master Code
#include <Wire.h>

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

void loop()
{
  Wire.beginTransmission(0x22); // Start communication with Arduino slave at address 0x22

  for(byte i=0;i<4;i++)
  {
    Wire.write(i);              // Request data from analog pin 'i'
    delay(5);                   // Give the slave a moment to sample ADC and respond
    while(Wire.available())
    {
      byte c = Wire.read();
      Serial.println(c);        // Print returned value to serial window
    }
  }

  Wire.endTransmission();       // End communication with Arduino slave
  delay(500);
}

Slave Code
#include <Wire.h>

void setup() {
  Wire.begin(0x22);
  Wire.onReceive(receivedHandler);
}

void loop() {
}

void receivedHandler() {
  byte data = Wire.read();
  byte analogValue;

  if(data == 0) analogValue = analogRead(A0)>>2;
  else if(data == 1) analogValue = analogRead(A1)>>2;
  else if(data == 2) analogValue = analogRead(A2)>>2;
  else if(data == 3) analogValue = analogRead(A3)>>2;
  else analogValue = 0;

  Wire.write(analogValue);
}

I can see that the data is being received by the slave, but the slave is not sending any data back, so I'm a bit confused how to send data back to the master. For the master there is "Wire.requestFrom(address, num of bytes)" to request a specific number of bytes, and for the slave "Wire.onRequest()" which will call a handler function to send back the number of bytes requested by the master, but for my application I won't be able to return more than 1 byte at a time.

If all you have to do is send 1 byte value for each of the 6 pins and your response from slave may be 32 bytes long, why not return ALL values, comma separated, and parse the answer on your master?  Thats what I do in these cases.  Treating multiple requests can make for lots of coding to get things right.

Bidirectional communication in I2C is a two stage thing.
First you have to tell the slave which pin (or register) you want to read. Then you have to read it.
A typical master sequence would be:
Wire.beginTransmission(0x22);
Wire.write(1);
Wire.endTransmission();
Wire.requestFrom(0x22, 2);
byte b1 = Wire.read();
byte b2 = Wire.read();

And of course your slave has to respond to the write() and remember which pin is being selected, then separately respond to the requestFrom() and return the data corresponding to the pin that was selected earlier.


text:
Can I make a USB Device with only data output
This is about how USB ports/devices work
Lets say i have a USB port on my computer

If I have an arduino board or something similar, am I able to connect output to Data+ and sort of make my own USB keyboard.
What I aim to achieve is send without having to receive

1) Would I need to connect it to both D+ and D- so it forms a circuit in order for the USB port to read the data? (or would the data simply be read and then disappears so I don't have to worry about two wires?)
If Yes: 2) If I manage to forcefully push electricity through the wire onto the Data pins, would I only need one wire?
Else: 3) is this physically impossible and the whole universe would explode if I tried?

There are no separate data input and output pins. So no, you can't.

The "B" is USB stands for Bus. It would be worth a read to understand how a bus is different to, for example, a serial port (where this sort of thing could work).

D+ and D- are not send and receive. The two signals are complementary to each other and bidirectional.
They form a low voltage differential pair. When one is high the other is low and vice versa.
Both have to be connected for USB signals to get through.
The data is sent down both wires at once, but only in one direction at a time (half duplex).
There is far more data going through USB than the data you are sending. The data you see is the end result of a complex protocol negotiation between your device and the host.

Thanks! it's a great answer. Am I able to only transmit data without receiving? I am able to connect to both D+ and D-, but I can only output data from my board, it doesn't receive data. For example, I'll just hardcode transmit the right data at the times I know when I should transmit, so i don't need to listen to the computer?

It is up to you what data is sent over the connection and in what direction. If you don't send data between the computer and the device then there is nothing for the device to read.

USB is a host-managed protocol. A USB device must be able to receive in order to operate, since the host notifies the device when it should send data back to the host.
The D+ and D- lines are not independent; the signaling state of the line is determined by examining both lines regardless of whether the host or the device is transmitting.
USB Made Simple


text:
Performing multiple Wire.writes() - does endtransmission slow things down?
Here's a question for anyone knowledgeable of the ways of I2C.
I'm curious about sending multiple writes to a device and was looking at the code for a MPU9250 module.
There is a nice library that compiled straight off the shelf by Kris Winer here.
In one of his code examples he makes multiple calls to a function called writeByte():
// Wire.h read and write protocols
void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
{
    Wire.beginTransmission(address);  // Initialize the Tx buffer
    Wire.write(subAddress);           // Put slave register address in Tx buffer
    Wire.write(data);                 // Put data in Tx buffer
    Wire.endTransmission();           // Send the Tx buffer
}

here is a (truncated) example of the code calling writeByte():
void initMPU9250()
{
  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00);
  delay(100);

  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);
  delay(200);
  writeByte(MPU9250_ADDRESS, CONFIG, 0x03);
  writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x04);
  .
  .
  .
  etc
}

My question is why call Wire.endtransmission() each time your sending I2C to the same device? I can see one reason straight off the bat which is you may need to call delay after your write() - but in cases where you do not need to call delay, wouldnt it be faster to do something like:
Wire.beginTransmission(address);
Wire.write(data1);
Wire.write(data2);
Wire.write(data3);
Wire.write(data4);
Wire.endTransmission();

at least when it's possible?

Nothing happens with Wire until you do call endTransmission(). If you don't call it then nothing will happen - bytes will just get buffered until the buffer overflows.

that makes sense, but how much over head is associated with the endtransmission between bytes versus running them all in and then calling endtransmission? In my case I'll send a block of six bytes total.

100% of the work is in endTransmission. There is no "overhead", it's where the transmission takes place. If what you are sending to can cope with you sending lots of bytes together then you could batch them up and do an endTransmission afterwards, but it's not the endTransmission that you are then optimizing, it's the sending of the address (beginTransmission) that you are optimizing. But it all depends on if the device you are sending to understands what you are doing in that case - most I suspect will not.

Its a reasonable question, but no (as others will explain).

No, Wire.endTransmission() doesn't "slow things down". It is, however, critical to the operation of the Wire library.
When you do a Wire transaction all the data you send is first buffered in an internal array. Only when you call Wire.endTransmission() does that data actually get sent out. The actual Wire.endTransmission() doesn't add anything extra to the transmission though.
In your example you are sending a total of 5 bytes (address + 4 data bytes) plus start/ACK/stop bits. In general most devices require you to send specific numbers of bytes in a specific order - the most common being a register address followed by the content of that register. That means 3 bytes. Any more bytes after that in the same transaction will either be ignored or would overwrite the first bytes.
Some devices though would allow <address><value><address><value> to be sent, thus removing the need for the repeated I2C address byte for the device each time. Many won't though.
Other devices (most notably flash memory or SRAM chips) would allow you to do page mode accesses, which would be <address><data1><data2>...<dataN> where the address would automatically increment for each data byte. Again, some may, some won't.
It is entirely down to the device you are sending data to as to whether you are able to batch together multiple blocks of data, and the form that batching has to be in if it is supported at all. So you should look in the datasheet for the device to see just what it can support.

Might need to mention the internal buffer in Wiring. The size of that buffer will limit the interaction.

Thank you Majenko - the other device in question is a atmega328p running the wire library. I'll try to work out how well it deals with serial Wire.write()s. Thanks.

@OwenWhite Then it is up to you how you create the protocol. If you program it to cope with multiple batched writes then it can cope with multiple batched writes.

I have just dug out the source to Wire to find the maximum buffer size: 32 bytes. That doesn't include the I2C device address, which is stored separately.

Thanks very much for your help. Actually I use the i2c_t3 which looks like the tx buffer length 258. Thanks very much for your comments.

authors: Роман Лазарев


text:
Burn arduino bootloader using ubuntu 16
I get the following error when I try to burn the arduino bootloader on an atmega328 mcu:
avrdude: verification error, first mismatch at byte 0x0000
         0xfd != 0x05

I am using an Arduino as ISP programmer. My computer runs Ubuntu 16.
This did not happen when I was using Ubuntu 14. I also tested it on another machine with Ubuntu 14 and this error does not appear. Seems to be something with Ubuntu 16. I installed Arduino IDE using the out of the box repo.
The avrdude command launched by the IDE is:
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -cstk500v1 -P/dev/ttyUSB0 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0x05:m -Uhfuse:w:0xde:m -Ulfuse:w:0xff:m

Am I safe replacing the -Uefuse:w:0x05:m with -Uefuse:w:0xfd:m ?? If answer is yes how can I get the IDE to do this correctly?
Uploading a sketch works pretty well.

This is not a real answer.
I have the same problem on Os X, but I can upload sketch via "upload using programmer", but this way I have no bootloader.
Problem arises only when trying to install boot loader.
I didn't have this problem some years ago on Linux Debian.
I your problem is solved, please let us know.

There is no functional differences between an efuse setting of 0x05 and 0xfd, as only the three lowest bits actually exist.  Your actual problem is elsewhere.

I had same problem and I think I have solved it.
In boards.txt file, I had:
##############################################################

diecimila.name=Arduino Duemilanove or Diecimila

diecimila.upload.tool=avrdude diecimila.upload.protocol=arduino

diecimila.bootloader.tool=avrdude diecimila.bootloader.low_fuses=0xFF
diecimila.bootloader.unlock_bits=0x3F
diecimila.bootloader.lock_bits=0x0F

diecimila.build.f_cpu=16000000L diecimila.build.board=AVR_DUEMILANOVE
diecimila.build.core=arduino diecimila.build.variant=standard

## Arduino Duemilanove or Diecimila w/ ATmega328
## --------------------------------------------- diecimila.menu.cpu.atmega328=ATmega328

diecimila.menu.cpu.atmega328.upload.maximum_size=30720
diecimila.menu.cpu.atmega328.upload.maximum_data_size=2048
diecimila.menu.cpu.atmega328.upload.speed=57600

diecimila.menu.cpu.atmega328.bootloader.high_fuses=0xDA
diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0x05
 diecimila.menu.cpu.atmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

diecimila.menu.cpu.atmega328.build.mcu=atmega328p

## Arduino Duemilanove or Diecimila w/ ATmega168
## --------------------------------------------- diecimila.menu.cpu.atmega168=ATmega168

diecimila.menu.cpu.atmega168.upload.maximum_size=14336
diecimila.menu.cpu.atmega168.upload.maximum_data_size=1024
diecimila.menu.cpu.atmega168.upload.speed=19200

diecimila.menu.cpu.atmega168.bootloader.high_fuses=0xdd
diecimila.menu.cpu.atmega168.bootloader.extended_fuses=0x00
 diecimila.menu.cpu.atmega168.bootloader.file=atmega/ATmegaBOOT_168_diecimila.hex

diecimila.menu.cpu.atmega168.build.mcu=atmega168

##############################################################

I have replaced the line containing:
diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0x05

with:
diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0xFD

Everything is ok now.
I can install boot loader on an ATMEGA328P (with an usbasp programmer), and I can install sketchs after that (via usb serial).
I don't know if it's the best way to solve the problem, but it works.
Hope this will help you, if not already solved.

As there are only 3 bits in the extended fuses of an ATmega328p, 0x05 and 0xFD are actually the same value as far as the bits that exist.  Different ways of handling the non-existent bits account for on the only difference, which is irrelevant.


text:
Blue pill acting as if it had 10bit ADC
I just got myself a STM32F103C8 Blue pill board. I am having funny behaviour with the analog readings. It behaves as if the unit was 10bits and not 12 bits.
I uploaded the very trivial Arduino code below. Just to read the analog input A0.
void setup() {
  Serial.begin(38400);
}
void loop() {
  Serial.println(analogRead(A0));
  delay(1000);
}

If I connect pin A0 to the 3.3v I get this output below.
1022
1022
1023
1022
1022
etc...

If I connect to a 1.5V source the above values becomes around 500.
It all behaves as if it was 10bits really which I fail to understand. Any ideas why?

Adding the following line in the setup() section solves the problem.
analogReadResolution(12)

Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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


text:
Replace digitalWrite with a selective bitwise operation
I have the following code with digitalWrite I aim to write with bitwise operation only.
No portability concerns here whatsoever. (for atmega328p here)
#define DATAOUT 11//MOSI
byte commandbits = B11000000;
for (int i = 7; i >= 3; i--) {
    digitalWrite(DATAOUT, commandbits & (1 << i));
}

I came up with something like this below which works.
#define DATAOUT 11//MOSI
byte commandbits = B11000000;
for (int i = 7; i >= 3; i--) {
    PORTB = (PORTB &(~(1<<3))) | (((commandbits &(1 << i))>>i) << 3);
}

Is this the most concise way. Is there a way to simplify it?

You do know that your code makes no real sense, don't you? Outputting data from a single pin like that can never do anything useful. You need a clock signal (synchronous serial) or for both ends of the connection to agree fairly precise timing (asynchronous serial). Or have you just omitted that part of your code for brevity?

I have omitted lots of it for brevity. obviously...

That's OK then. I'll let you off.

Personally I'd expand it out a little:
if (commandbits & (1 << i)) {
    PORTB |= (1<<3);
} else {
    PORTB &= ~(1<<3);
}

It's far more readable, and there are less shifts to mess around with. Plus the AVR has bit set and bit clear operations which that will make use of, especially since it's now using literal values. You could actually replace those values with literals:
if (commandbits & (1 << i)) {
    PORTB |= 0x08;
} else {
    PORTB &= 0xF7;
}

That was my first idea of it. I did not mention it but the faster the better in my case. I'll have to do a timing test of the one liner vs if else.

if you want fastest you need to look at the assembly code the compiler produces. I think the if statement would actually be faster than your code. AVRs can only do single bitshifts, so <<3 would be three instructions. Note that compilers are pretty smart. So don't bother replacing (1<<3) with 0x08 thinking it will be faster.

I confirm the if else is much faster. Thanks for your input Majenko and Gerben.

If you like both portability, readability and performance there are a few libraries (for instance Arduino-GPIO):
#include "GPIO.h"

GPIO<BOARD::D11> data;

// Setup
data.output();

// Manual loop unrolling for speed. Could ask the compiler to do this
// Member function write()
data.write(commandbits & 0x80);
data.write(commandbits & 0x40);
data.write(commandbits & 0x20);
data.write(commandbits & 0x10);
data.write(commandbits & 0x08);

// Or using the assignment operator
data = commandbits & 0x80;
data = commandbits & 0x40;
data = commandbits & 0x20;
data = commandbits & 0x10;
data = commandbits & 0x08;

And it is as fast as manually written direct port access.

Interesting. Your example get me thinking I should better get rid of the for loop and replace the (1<<i) with their value.


text:
Capturing avrdude command in IDE
With verbose upload selected the IDE provides the executed avrdude command at the top of the log.
I am interested in copy pasting that avrdude command. However at the end of the upload the command is not available anymore. The IDE only shows some last lines of the log and discard the top part.
Is that log saved anywhere? (I am on ubuntu). Any ideas how I can get that command?

If you run the IDE from a terminal you should get the output to STDOUT in your terminal to do with what you want.

That's the solution. Thanks a lot. I am using arduino | tee cmd.txt to capture it.

Disconnect the arduino from your PC before pressing upload. That way you get less output and it won't overwrite the top lines.

If you run the IDE from a terminal you should get the output to STDOUT in your terminal to do with what you want.


text:
Trying to make a wattmeter
I've been trying to make a wattmeter using arduino but cannot find the shield I need to buy to put onto my arduino to make it. There are no such parts in the Arduino Store and online the best I could find is this. This measures the arduino's energy consumption, however, not other things. I am really new at this and thoroughly lost. I would be really glad if someone could help me with this problem :)

i've built a ton of "things", but i've never used a shield; don't be limited by less than your imagination. the next-simplest is to look for "modules" aka "bricks". there are plenty of Hall-effect based current sensors on ebay, and voltage just needs a few resistors to measure.

Where did you get that the linked shield only measures Arduino's energy consumption? It is clearly stated that it connects up to three AC current sensors.

You will need an Ampere meter and a Voltmeter. Watts is Volt * Ampere.
There are logic level compatible units out there for ampere meters ranging from a few mA to at least dozens of Amperes.
Also for voltmeters there are several logic level compatible units available, to plug in your project.
The rest is math. (Watts = A * V )

P=VI for DC, or for AC with a purely resistive load. For AC with other kinds of loads you should include the power factor.

Yes, that's perfectly true. I just assumed, it'll be DC.


text:
Correct Capacitors to use with L7805 Voltage Regulator
I am making my own arduino.  I am in the process of hooking up power to the Atmega328.
In both these articles they use the L7805 voltage regulator with two 10uF capacitors.
https://www.arduino.cc/en/Main/Standalone
http://www.instructables.com/id/How-to-Build-an-Arduino-Uno-on-a-BreadBoard/?ALLSTEPS
I am looking at the datasheet for the regulator at http://pdf.datasheetcatalog.com/datasheet_pdf/sgs-thomson-microelectronics/L7805CD2T_to_L7885CV.pdf
The data sheet provides a number of figures for how to correctly hook up the L7805 in different situations (pages 4, 16-23).  I think Figure 13 represents our situation (Fixed Output Regulator).  In the figure they use 0.33uF and 0.1uF
capacitors.  Could someone explain why the examples use 10uF and the data sheet specifies 0.33uF and 0.1uF?

on a fixed voltage regulator, it's typically not critical. adjustable ones might want a certain rage to avoid oscillation, to speed feedback, or to allow faster output voltage adjustments on high-impedance circuits. if something uses a constant rate, it needs less output buffering. if input voltage is already smooth, it needs less input smoothing. fwiw, the 7805 usually seems ok w/ none.

The answers are in the notes:

Although no output capacitor is need for stability, it does improve transient response.
Required if regulator is locate an appreciable distance from power supply filter.

So  the values aren't critical to the operation, but you should have them there. Bigger capacitors give more energy to the regulator and more energy to your circuit (input and output capacitors respectively) but at the cost of lower frequency response. The actual values you select depend on your circuit, not the regulator. 10µF is a good "ballpark" figure to use in most circumstances.
The input capacitor reduces the impedance of the power source by providing a local source of power. The output capacitor is like the "reservoir" capacitor you should have at the power entry to all boards anyway, and reduces the impedance to the rest of your circuit.
For the higher frequency responses you should have smaller value decoupling capacitors by all your active components anyway.
You can also add more smaller capacitors to the output of the regulator to improve high frequency responsiveness if needed - you're not just limited to the one capacitor.

Why are specific values specified in the data sheet if they are not dependent on the regulator?  In general how\where would one go to learn about choosing an appropriate value for their circuit?

I have no idea why they have specified values. Maybe they are the minimum to use if you do use them (which you should). Unless you have specific requirements 10µF is a good enough value. Maybe add a 100nF on the output as well.

When you say maybe a 100nF on the output as well, are you saying put both capacitors between the Vout and ground?

Yes, in parallel.

Neat answer! I've had problems with an GSM transceiver, that only worked on "new" rechargable batteries. Near the end of the project, it wouldn't work anymore. It seemed that the internal impedance of the battery had risen and couldn't supply the sudden burst of power required. (The designer actually said: "well it did work and the battery can deliver 2A so it should be OK, you should check your code again"). Spend quite some time to figure this out as I was more into embedded software as in hardware. Moral of the story, better be safe than sorry ;D

Could someone explain why the examples use 10uF and the data sheet specifies 0.33uF and 0.1uF?

One obvious reason is that those two examples are non compliant with the datasheet.
But generally speaking the ordinary 78xx regulators use emitter output and are quite tolerant to the output capacitance. 10if is not a bad number.
However, there are also variants of 78xxx that take their output from the collector. They are more sensitive to output capacitance, as most ldos are.
Generally it is a good idea to stay within the datasheet but that doesn't mean you shouldn't step out from time to time.

I wonder how such regulator would work well with a lot of distributed capacitance on a PCB - a TTL graveyard comes to mind (though probably less relevant these days). 100 nF are easily exceeded.


text:
Power Supply Ticking, Light Flashing
My Arduino came with a 9V 1A power supply to use with it.  I decided to test it out with my multimeter.  I put the red lead in the connector and the black on the outside.  Sure enough I read 9V.  However when I tested the amps this did not work.  The meter read a low value and the power supply started making a ticking noise and a light started flashing on it.
I did have the multimeter on the correct settings.  Looking online I now realize that you cannot test the amps this way and as I was essentially testing a circuit with no load on it.
What I would like to know is what the power supply was doing when it was ticking and flashing.  It is alive and well so I suppose it was some sort of internal protection.

It was "hiccuping" in order to prevent damage from the short circuit condition. Once the short circuit condition is removed, the PSU restores normal operation.
From the reference:
"The operation of hiccup is as follows. When the current-sense circuit sees an over-current event, the controller shuts off the power supply for a given time and then tries to start up the power supply again. If the over-load condition has been removed, the power supply will start up and operate normally; otherwise, the controller will see another over-current event and shut off the power supply again, repeating the previous cycle."

I was essentially testing a circuit with no load on it.

No, you were imposing a very high load. An ammeter (amp meter) should be in series with the circuit under test. For example:
----(-)-- Power supply (+)-----(+)- Amp meter (-)---|
|                                                   |
|                                                   |
---(-)---- Circuit under test ----(+)----------------

When in amps mode the meter has a very low resistance, and measures the voltage drop over that low resistance (probably 0.1 ohms or less). Thus putting the meter across the power supply shorts it out.
Hence the noise it makes while trying to recover. The power supply turns itself off and on until the short goes away.
Also you are lucky you didn't blow the fuse in your meter. They are normally fused in case you accidentally do something like that.

Isn't low resistance considered a low load and not a high load?

A low resistance in series is a low load. A low resistance in parallel is a high load.
Assuming your meter presented a resistance of 0.15 ohms on the 10A range (as mine does) then using Ohms Law we can see that this would give a current of:
I = V / R
I = 9 / 0.15
I = 60 amps

So, you are trying to draw 60 amps from your 1A power supply, which then turns off.

If the multimeter is rated at 10A and the power supply can provide at most 3A, then why is there a risk of blowing the fuse in the meter?

It depends on the range on the meter. Mine has a 10A range and a milliamp range. The 10A range is fused to slightly more than 10A (naturally) and the milliamp range has a maximum of 400 mA. If you had tested with the milliamp range you would have blown the fuse. Yes, it would survive on the 10A range, if your power supply cannot output 10A.
There will be lots of web pages about measuring amps with a meter, here is one.

Thanks for the info.  Could you clarify a little further to help me understand?  Isn't low resistance considered a low load and not a high load?  If the multimeter is rated at 10A and the power supply can provide at most 3A, then why is there a risk of blowing the fuse in the meter?

See amended answer.


text:
exit status 1 expected primary-expression before 'int'
int temp=A0;
#include<stdlib.h>
#include <SoftwareSerial.h>

#define SSID "rab"
#define PASSWORD "rakesh1234"
#define IP "184.106.153.149" // thingspeak.com
String GET = "GET /update?key=B8B8E4FC1K541QZQ&field1=";
SoftwareSerial monitor(0, 1); // RX, TX
SoftwareSerial mySerial(5, 6); // RX, TX
int p1=0,p2=0,p3=0;
int i=0;
int j=0;

void setup() {
  pinMode(A0,INPUT);
  Serial.begin(115200);
  monitor.begin(115200);
  mySerial.begin(9600);
  sendDebug("AT");
  delay(2000);
  if(Serial.find("OK")) {
    monitor.println("RECEIVED: OK");
    Serial.println("RECEIVED: OK");
  }
  connectWiFi();
}

unsigned char buf[50];

void loop() {
   while(!mySerial.available());
   if(mySerial.read() == '#') {
     for(int i=0;i<12;i++) {
       while(!mySerial.available());
       buf[i] = mySerial.read();
     }
     buf[3] =0;
     buf[7]=0;
     buf[11]=0;
     p1 = atoi((const char *)&buf[0]);
     p2 = atoi((const char *)&buf[4]);
     p3 = atoi((const char *)&buf[8]);
     delay(1000);
   }

   long int SensorValue=analogRead(temp);
   SensorValue=SensorValue*5000;
   SensorValue=SensorValue/1024;
   SensorValue=SensorValue/10;
   SensorValue=SensorValue*9;
   SensorValue=SensorValue/5;
   SensorValue=SensorValue+32;
   String tempF=String(p1);
   String tempFF=String(p2);
   String tempFFF=String(p3);
   String tempFFFF=String(SensorValue);

   for(int j=0;j>-1;j++) {
     **j= Serial.read(int p1, int p2, int p3);**
   }
   while(Serial.available()==j)
     updateTemp(tempF,tempFF,tempFFF,tempFFFF);
   while(1) {}
 }

 void updateTemp(String tempF1 ,String tempF2, String tempF3,  String tempF4) {
   String cmd = "AT+CIPSTART=\"TCP\",\"";
   cmd += "api.thingspeak.com";
   cmd += "\",80";
   sendDebug(cmd);
   delay(1000);
   if(Serial.find("Error")) {
     monitor.print("RECEIVED: Error");
     Serial.print("RECEIVED: ERROR");
     return;
   }
   cmd = GET;
   cmd += tempF1;
   cmd += "&field2=";
   cmd += tempF2;
   cmd +="&field3=";
   cmd +=tempF3;
   cmd +="&field4=";
   cmd +=tempF4;
   cmd += "\r\n";
   Serial.print("AT+CIPSEND=");
   Serial.println(cmd.length());
   if(Serial.find(">")) {
     monitor.print(">");
     monitor.print(cmd);
     Serial.print(cmd);
   } else {
     sendDebug("AT+CIPCLOSE");
   }
   if(Serial.find("OK")) {
     monitor.println("RECEIVED: OK");
   } else {
     monitor.println("RECEIVED: Error");
   }
 }

 void sendDebug(String cmd) {
   monitor.print("SEND: ");
   monitor.println(cmd);
   Serial.println(cmd);
 }

 boolean connectWiFi() {
   Serial.println("AT+CWMODE=1");
   delay(2000);
   String cmd="AT+CWJAP=\"";
   cmd+=SSID;
   cmd+="\",\"";
   cmd+=PASSWORD;
   cmd+="\"";
   sendDebug(cmd);
   delay(1000);
   if(Serial.find("OK")) {
     monitor.println("RECEIVED: OK");
     return true;
   } else {
     monitor.println("RECEIVED: Error");
     return false;
   }
 }

This is my code. I am getting an error as "exit status 1
expected primary-expression before 'int'"
Please help me.
Thank you.

Please reformat your code properly so we can read it. Also, what line number does the error happen at?

You are doing Serial.read() wrong with:
Serial.read(int p1, int p2, int p3);

Serial.read() takes no parameters per https://www.arduino.cc/en/Serial/read
Maybe you want to try parseInt() instead?

authors: Алексей Харичкин


text:
How long does it takes for arduino to reach main()?
I am trying to emulate the behavior of a circuit using an Attiny85
This is the result I got so far:

In the picture above, D2 is VCC, D4, D5 and D6 are outputs of the circuit I am trying to emulate. D7 is the output of Attiny85
The code I am using is:
#define F_CPU 8000000L
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

int main() {

  DDRB = 0b00001000;

  PORTB = 0b00001000;
  _delay_ms(5);

  PORTB = 0b00000000;
  _delay_ms(5);
  PORTB = 0b00001000;
  _delay_ms(5);

  PORTB = 0b00000000;
  _delay_ms(5);

  _delay_ms(5);

  while(1)
  {
     PORTB = 0b00001000;
    _delay_ms(1);
     PORTB = 0b00000000;
    _delay_ms(1);
  }
    return 0;
}

According to this, it takes roughly 64ms from powerup until it actually run the main program.
Is there any reason for such a delay? How can I reduce it somehow (ideally to 20ms or less)?

do you use a bootloader or you program it over ISP?

Sorry, forgot to mention - yes, I programmed over a ISP (usbtiny) to make sure the bootloader is not active

The ATtiny85 has a built-in delay counter that keeps the MCU in reset
mode for some time after the power is applied. This seems to be intended
as a wait for the clock and power to be stabilized. The length of this
delay depends on your selected clock source, and is somewhat
configurable with the fuses.
According to your code, your MCU is clocked at 8 MHz. I assume you
are then using the internal RC oscillator as a clock source. If this is
the case, you have three choices for the startup delay:

20 CPU cycles
20 CPU cycles + 4 ms
20 CPU cycles + 64 ms

The latter is recommended if your power rises slowly, and is the default
configuration in which these MCUs are shipped. If you power level rises
fast, you may want to select a shorter delay by programming the SUT
fuses. See the datasheet for details (section System Clock and Clock
Options → Clock Sources → Calibrated Internal Oscillator).

You are right - my L fuse was programmed as 0xE1 (PLL clock, 64ms delay). I changed it to 0xD2 (Internal clock, 8Mhz, 4ms delay) and it worked


text:
How to blink 2 led strips without delay
Hi all I use 2 sensors and 2 led strips. I want to let both led strips light up without interrupting each other while reading the different values from the inputs. But Arduino still pauses when one lights up, the other one needs to wait for the time to pass, either one misses reading the value when one is processing the output.
I know delay(wait); makes it block out the coming data, but it lets the strips light up for 6 seconds. If I remove it, the strips will light one 1 second only. What should I do? Thanks so much!
#include <Adafruit_NeoPixel.h>
#define PIN 6
int ledFadeTime = 7;
Adafruit_NeoPixel strip3 = Adafruit_NeoPixel(60, 9, NEO_GRB +NEO_KHZ800);//led pin
Adafruit_NeoPixel strip4 = Adafruit_NeoPixel(60, 7, NEO_GRB + NEO_KHZ800);//led pin
const int sensorPin3 = A2;//motion sensor
const int sensorPin4 = A3; //flash sensor

unsigned long strip3OnTime;
unsigned long strip4OnTime;
bool strip3On;
bool strip4On;
unsigned long previousMillis = 0;
const long interval = 1000;

void setup() {

  Serial.begin(9600);
  strip3.begin();
  strip3.show();
  strip4.begin();
  strip4.show();

  strip3On = false;
  strip4On = false;
}

void loop(){
 int Val3 = analogRead (sensorPin3); // sensor val
 int Val4 = analogRead (sensorPin4);

 Serial.print(Val3);
 Serial.print(" ");
 Serial.println(Val4);

   if (Val3>70) {
     rgbFadeInAndOut3(0, 0, 255, ledFadeTime);
     //analogWrite(strip3, HIGH);
     strip3On = true;
     strip3OnTime = millis();
   }
   if (Val4>70) {
     rgbFadeInAndOut4(0, 0, 255, ledFadeTime);
     //analogWrite(strip4, HIGH);
     strip4On = true;
     strip4OnTime = millis();
   }

   if(strip3On)
     if(millis() - strip3OnTime > 7000) {
       rgbFadeInAndOut3(0, 0, 1, 5000);
       strip3On = false;
     }
   if(strip4On)
     if(millis() - strip4OnTime > 7000) {
       rgbFadeInAndOut4(0, 0, 1, 5000);
       strip4On = false;
     }
 }

 void rgbFadeInAndOut3(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
   unsigned long currentMillis = millis();
   if (currentMillis - previousMillis >= interval){
     previousMillis = currentMillis;

   for(uint8_t b = 0; b <255; b++) {
      for(uint8_t i=0; i < strip3.numPixels(); i++) {
         strip3.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
       }
      strip3.show();
     delay(wait);
   };

   for(uint8_t b=255; b > 0; b--) {
      for(uint8_t i = 0; i < strip4.numPixels(); i++) {
         strip3.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
      }
      strip3.show();
      delay(wait);
   };
 };
 }
 void rgbFadeInAndOut4(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval){
     previousMillis = currentMillis;

   for(uint8_t b = 0; b <255; b++) {
      for(uint8_t i=0; i < strip4.numPixels(); i++) {
         strip4.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
      }
      strip4.show();
      delay(wait);
   };

   for(uint8_t b=255; b > 0; b--) {
      for(uint8_t i = 0; i < strip4.numPixels(); i++) {
         strip4.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
      }
      strip4.show();
      delay(wait);
   };
 };
 }

Blink without delay.

I advice to take a look at this;
link

Very simple. It takes only 3 steps.

Blink an led stripe with no delay.
Blink two led stripes, using the code developed in step 1.
Enjoy your blinking let stripes.

edit: since you seem to be struggling, here is one (of countless) way(s) to do #1 above.
//blinky_ledx2.ino

//blink two led strips independently

//blinky rate
#define LED_DLY         100     //duration for led1, in ms
#define LED             12      //led to be blinked

int led = 13;

//run user routine, non-blocking
void NB_run(void (*func_ptr)(void)) {
    static uint32_t millis_next=0;                          //next match point

    if (millis() >= millis_next) {                          //time is up
        millis_next += LED_DLY;                             //advance match-up time
        func_ptr();                                         //execute user function
    }
}

//blinky example
void blinky1(void) {
    //blink LED
    digitalWrite(LED, !digitalRead(LED));
}

void setup() {
    // put your setup code here, to run once:
    pinMode(led, OUTPUT);
    pinMode(LED, OUTPUT);                                   //LED as output
}

void loop() {
    NB_run(blinky1);                                        //run blinky1 at set intervals for LED
    digitalWrite(led, !digitalRead(led));                   //blink led
}

the heart of this is NB_run() -> it executes func_ptr() once the set time has been reached. otherwise, it returns without doing anything, as shown in the example below.
D13 is blinked constantly in the main loop, while D12 is blinked based on LED_DLY, in a non-blocking fashion.

I purposely wrote NB_run() so that it needs additional "parameterization" to run multiple tasks - what you have here is the basis of a generic framework for a rudimentary pseudo multi-tasker. it is not difficult at all for you to extend the code to run 2 stripes.
good luck.
edit2: it was pointed out to me, quite correctly, that something like this can be done via rtos. true, but a typical rtos has lots of overhead and requires a more substantial hardware to support.
one exception is macro-based rtos, like protothread. in that particular implementation, you will see that there is little gain in terms of code complexity, but some stylistically.
here is an implementation of running two tasks concurrently via protothread, only code for one task is shown, however.
//thread 1
PT_THREAD(protothread1(struct pt *pt, uint32_t pr)) {
    static uint32_t time_next=0;        //time for the next blinking

    PT_BEGIN(pt);
    while (1) {
        PT_WAIT_UNTIL(pt, millis() > time_next);
        time_next += pr;                //advance time to the next match up point
        toggleLED(LED1);                //run user task - blink led1
    }
    PT_END(pt);
}

void loop() {
    protothread1(&pt1, LED1_DLY);       //running thread1
    protothread2(&pt2, LED2_DLY);       //running thread2

}

you can see that it retains largely the code structure presented earlier.
here is the outcome of that code, blinking D12/D13 at different rates.

I added a function for light animation, void rgbFadeInAndOut3 & void rgbFadeInAndOut4  are set to be 6 seconds, if I remove delay, the animation is going to reduce to 1 second, and it's still blocking the coming data.

it's still blocking the coming data.... because you continue to use delay. as long as you do that, you will never get the kind of behaviors you want.


text:
Using Analog Comparator on Uno to Read Differential Voltage Signaling
I am trying to use the Arduino Uno to read an AVCLan bus on a Toyota vehicle.  Logic 0 is when +/- drive are 120mV or more apart, and logic 1 is 20mV or less.  See Toyota AVC-Lan description.
I currently set the TCNT1 timer to /1 prescaler for resolution, and waiting in a loop until the ACO bit sets in ACSR.  Using this, I measure the amount of time the signal was logic 0, and calculate each bit based on the how long the timer ran, and then resetting it.
While this works fine for most messages, I do receive a "glitch" every couple messages, with on-times around 2uS - 4uS, which shouldn't happen on this bus.  I'm guessing the analog comparator is tripping up if the drive is around 10mV - 20mV, when it shouldn't set.
Is there any way to set up a threshold, so that it will only fire the comparator at say 100mV or above?

I think what you want is a 2-stage system consisting of a differential amplifier to convert the signal into a single-ended signal, then a comparator to compare the single-ended voltage with a reference voltage.

@Majenko I suggest you transform your comment into an answer

@RobertoLoGiacco I will when I get round to working out a suitable schematic for it.


text:
Decoding RF Signal
I have a motorized curtain and I'm trying to understand its rf control signal in order to control it from my arduino.
I got the times, and checked the code is not static. I believe it has some kind of "sequencial counter" but I could not decode and understand the logic. In resume, I'm trying the get the operations the manufacturer do in order to obfuscate the payload.
The timings I got for the same key, pressed in sequence, are:
396,400,396,804,396,408,800,800,396,408,396,408,396,408,396,408,800,400,400,796,404,400,804,800,804,396,400,800,804,800,400,400,404,404,400,404,400,400,404,400,804,396,404,796,24508,408,368,404,368,404,368,404,368,400,376,400,372,400,372,400,372,400,372,400,372,400,372,400,372,400,376,396,372,400,372,404,372,392,380,396,376,396,376,400,376,392,376,396,376,400,3872,396,384,392,384,420,384,420,384,420,384,416,792,408,388,812,388,416,388,416,388,416,388,416,388,412,796,408,392,400,392,408,392,808,388,412,392,412,392,412,796,404,396,804,796,404,392,404,392,404,396,804,796,404,396,400,396,804,800,400,396,400,396,400,396,804,396,408,800,804,392,408,396,408,396,408,396,408,800,400,400,800,396,408,804,796,804,396,400,800,804,800,400,404,400,404,400,400,404,404,400,400,808,392,404,796,24516,404,368,404,368,404,368,404,368,400,372,404,368,404,372,400,372,400,372,400,372,400,372,400,372,396,376,400,376,396,376,396,376,400,372,400,372,396,376,396,376,400,376,396,372,404,3868,400,380,392,384,420,384,416,388,420,384,420,788,408,388,812,388,416,388,416,388,416,384,416,392,412,796,404,392,404,392,404,392,804,396,416,388,408,396,412,796,404,392,808,796,404,392,404,392,404,392,808,796,400,396,400,400,800,804,400,392,404,396,400,396,800,400,404,804,800,396,408,396,408,400,400,400,404,804,396,404,796,400,404,804,800,804,396,400,800,804,796,400,404,400,404,400,404,400,400,404,404,804,392,404,796,24512,412,364,404,368,408,364,404,368,404,368,404,368,404,372,404,368,404,368,404,368,400,372,404,368,400,372,400,376,396,376,396,376,400,372,396,376,396,376,400,372,400,376,396,376,400,3868,400,380,392,384,420,384,416,388,416,388,420,788,412,384,816,384,416,388,416,388,416,388,416,388,416,792,408,388,404,392,408,388,812,388,416,388,412,392,412,796,400,396,808,796,404,392,404,396,400,396,804,800,400,396,400,396,804,800,400,396,400,396,400,396,804,396,408,800,804,396,404,400,408,396,404,400,404,804,396,400,800,396,408,804,796,808,396,400,796,808,796,400,404,400,404,400,404,400,404,400,400,808,392,404,796

392,412,796,400,396,404,396,800,396,408,396,408,396,408,396,408,396,404,400,408,396,404,804,396,400,396,400,396,400,800,804,800,804,396,400,800,400,404,804,796,404,400,400,404,404,400,804,396,404,392,404,392,404,380,24124,404,368,408,368,404,372,400,368,404,368,400,372,404,368,404,368,404,372,400,372,400,372,400,372,400,372,400,372,400,376,396,372,400,376,396,376,396,376,396,376,396,376,396,376,400,3872,396,384,392,384,420,384,420,384,420,788,408,392,404,388,412,388,808,388,416,388,412,392,416,792,404,396,404,388,808,800,808,388,412,392,412,796,404,392,400,400,400,396,400,396,400,396,404,392,400,396,404,396,400,396,400,396,804,396,408,796,404,396,400,396,800,396,412,392,408,396,408,396,408,396,408,396,408,396,408,800,396,400,400,400,396,400,800,804,800,800,400,400,800,396,404,808,796,400,404,400,404,400,404,804,396,400,396,400,396,404,380,24124,408,368,404,368,404,368,404,368,404,368,404,368,400,372,400,372,404,368,404,372,400,372,400,372,400,372,396,376,400,372,400,372,396,380,392,376,400,376,396,376,396,376,396,376,400,3868,400,380,392,384,420,388,416,388,412,796,408,388,408,388,408,388,812,388,416,388,412,392,412,796,408,388,408,388,812,792,808,392,408,396,408,800,400,396,404,392,404,392,404,392,404,392,404,396,396,400,400,396,400,396,404,392,804,396,408,800,400,396,400,400,800,396,408,396,408,396,404,400,408,396,408,396,404,400,404,804,396,400,400,396,396,400,800,804,800,804,396,400,800,400,404,804,800,400,404,400,400,404,400,808,392,404,392,404,396,400,380,24124,404,368,412,364,404,368,404,368,404,368,404,368,404,368,404,372,400,368,404,372,400,372,400,372,400,372,400,372,400,372,400,372,400,376,396,376,396,376,400,372,396,376,400,372,400,3872,396,384,392,384,420,384,424,380,416,792,408,388,408,388,412,384,816,384,416,388,416,392,416,788,408,392,404,392,808,796,808,388,416,388,416,792,404,396,404,388,408,392,404,392,404,392,404,392,404,396,400,396,400,396,404,392,804,396,408,800,400,396,400,396,804,396,408,396,408,396,408,396,404,400,404,396,408,396,408,800,400,396,400

This site helps visualize the timings  (just copy and paste)
I believe it uses modulation ASK and Manchester Encoding (not sure about that), and the binary data I got is (the timings for third key press I did not save):
1010101010100101101010101010010101011010101001011001010101100101011001010101101001101010101001011010011001011001101010101010010110

1010101010010101011010101001010110011010100101010101010101010101101001010110101010101010100101010110011001011010011010101001010101

1010101010011010101010101001101001011010100110101001010101011010011001010110010101101010100110101010011001011010101010101001101010

This link explain what I'm trying to do, but using a control from another manufacturer. The result, is better explained here.
If is useful, I press the same key 2 times in other identical control and the timings I got are (I believe it changes the address and the 'counter'):
408,400,408,400,412,396,408,396,416,400,816,388,412,792,820,796,816,792,416,396,820,384,412,796,416,388,416,396,412,396,416,392,412,396,820,384,420,788,24636,404,376,400,376,396,384,396,376,400,380,396,384,396,380,396,380,396,380,396,384,392,384,396,380,392,388,392,384,388,388,392,388,392,384,392,384,392,384,392,388,388,388,384,392,392,3900,392,392,384,396,412,396,408,404,412,392,412,804,404,400,804,400,408,404,408,396,408,400,412,396,408,808,400,404,400,400,400,404,800,404,408,400,404,408,400,812,392,408,804,400,408,400,404,408,400,408,400,816,800,404,400,408,400,816,800,408,400,408,400,404,404,816,388,412,796,408,400,408,400,408,396,412,400,412,396,820,388,412,792,820,792,816,796,416,392,820,388,412,796,412,396,412,392,416,392,416,396,416,388,824,384,416,792,24636,400,380,400,372,400,380,396,380,396,380,396,384,396,380,400,376,396,384,396,380,396,380,396,380,396,384,392,384,392,384,392,388,392,384,388,388,392,384,392,388,392,388,388,384,396,3896,392,392,388,396,408,400,412,392,416,396,412,800,404,400,808,396,412,400,408,396,412,400,408,400,408,804,400,404,400,400,396,404,808,400,408,400,408,404,404,808,396,404,804,404,400,408,400,408,404,404,404,812,800,404,404,404,404,816,796,408,400,408,400,408,400,816,388,412,792,412,400,412,396,412,396,412,396,412,396,820,388,412,792,820,796,816,796,412,392,820,392,412,792,416,392,412,396,416,392,412,396,416,392,824,384,420,788,24632,404,376,400,376,400,376,400,380,400,376,400,380,396,380,392,384,396,380,396,384,392,384,396,380,396,380,392,388,392,384,392,388,388,388,388,388,392,384,392,384,392,384,392,388,392,3896,392,396,384,392,416,396,408,400,412,396,412,804,400,400,808,400,408,400,408,400,408,400,408,400,408,808,396,404,396,408,396,400,804,404,408,400,408,400,404,812,396,404,804,408,400,404,400,408,400,408,400,816,800,408,400,408,400,812,800,408,400,408,400,408,400,816,388,412,800,408,396,412,396,412,396,412,396,412,396,820,388,412,796,816,796,816,792,416,392,820,388,420,788,412,396,416,388,420,392,416,392,412,396,820,384,420,788

808,400,400,396,408,396,404,804,404,404,404,400,408,404,404,404,404,404,404,404,812,392,408,796,412,400,408,400,816,392,408,392,408,388,412,800,412,392,412,400,408,400,816,388,412,388,412,392,412,388,412,796,816,796,412,396,820,792,820,796,408,396,412,392,416,396,820,388,412,384,420,384,416,372,24248,404,376,396,380,400,376,400,376,400,380,396,380,396,380,396,380,400,380,392,388,392,380,396,384,392,384,392,384,396,380,392,384,392,388,392,384,392,388,388,388,388,388,388,388,396,3896,392,392,388,396,408,400,412,396,412,800,404,400,404,396,400,404,804,400,408,400,408,400,408,808,400,404,396,404,800,812,804,400,408,400,404,812,400,404,396,404,396,404,804,400,408,404,404,404,400,412,400,404,404,408,400,816,388,412,792,412,400,408,400,816,388,412,392,412,388,412,796,412,396,412,396,408,400,816,392,412,388,412,388,412,388,416,792,820,792,412,396,820,792,820,792,416,392,416,392,416,392,820,388,416,384,420,384,416,368,24248,404,376,400,380,396,380,400,376,400,376,400,380,392,384,396,380,400,380,392,384,396,384,392,380,392,384,396,384,392,384,392,388,388,388,388,388,392,388,388,384,392,388,388,388,396,3896,392,392,384,396,416,396,412,396,412,800,404,400,404,396,400,404,808,396,408,400,408,400,408,804,404,400,400,400,808,808,800,404,408,404,400,816,392,408,396,404,396,404,804,404,400,408,404,404,404,404,404,408,396,408,404,812,396,404,800,408,400,408,400,816,388,412,392,412,388,412,796,408,400,408,400,408,400,816,392,412,388,412,388,412,388,416,792,820,792,412,396,820,792,820,792,416,392,416,392,416,392,820,388,416,384,416,384,416,372,24248,404,376,404,372,404,376,400,376,396,380,400,376,400,380,396,380,396,380,396,380,396,384,396,380,396,384,388,388,392,384,392,384,392,384,392,388,388,384,392,392,388,388,384,388,392,3900,392,396,384,396,412,396,412,396,412,804,404,396,404,396,404,400,804,400,408,400,408,404,408,808,396,400,400,404,804,812,800,404,404,404,404,808,400,404,396,404,396,404,804,404,404,404,404,400,404,408,404,404,404,408,396,816,392,404,804,408,400,408,400,820,384,412,388

Do you have a specific question?

you may have decoded  the first two data streams incorrectly .... i  got these      00000011000000111100001100000100010000110000001101010011000000110 .....
00000111100001110100011111111111001110000000011110101100100001111

What happens if you just replay the recorded data? Does the curtain not respond if the 'counter' isn't updated?


text:
Unable to connect esp8266 12 module with arduino uno
Here is what I am doing
Arduino(UNO)--------Esp8266
3.3 v -- vcc
TX      -- RX
RX      -- TX
3.3 v  -- EN(ch_pd)
GND     -- GND

there is no blinking of LED on Esp8266, sometimes the LED is on and sometimes it is not. And when I send "AT" command using Serial of Arduino IDE, only RX light of Arduino blinks, TX is not blinking and there is no response of that command. I am having 3.3 voltage on my Vcc pin of Esp8266 but the voltage on the TX and RX pins of Esp8266 is 5 volts, I know that i can reduce this to 3.3 voltage by using a voltage regulator but my question is why there is no blinking on the module even when i have supplied the proper 3.3 voltage and GND?
What's the difference between the blinking and a still LED on Esp8266?
I have tried every tutorial on internet. No help at all. Right now I am so exhausted that I want to quit.If you can help in solving the problem, I would be very thankful to you sir.

http://arduino.stackexchange.com/q/16917/972

The UNO runs on 5V and the ESP on 3.3V. When you send data to the ESP, you're sending it over 5V. When the ESP sends data to the UNO, it uses 3.3V. So, these voltages don't match. I suggest using a logic level converter to change the voltages of communication between the UNO and the ESP.

When you are using Arduino board just as USB --> RS232 converter to send AT commands from PC to ESP8266 you have to connect TX to TX and RX to RX. But when you want communication between microcontroler and ESP then you have to connect TX to RX and RX to TX. Here I explained that in details.


text:
connecting ESP8266 to mega 2056
im trying to connect wifi module to my MEGA 2560 board.
i set up the board as the picture bellow

and my program is as follows
#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(18,19); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different

  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

  pinMode(12,OUTPUT);
  digitalWrite(12,LOW);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);

  pinMode(10,OUTPUT);
  digitalWrite(10,LOW);

  sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
  sendCommand("AT+CWMODE=1\r\n",1000,DEBUG); // configure as access point
  sendCommand("AT+CWJAP=\"mySSID\",\"myPassword\"\r\n",3000,DEBUG);
  delay(10000);
  sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Server Ready");
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     esp8266.find("pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
     int secondNumber = (esp8266.read()-48);
     if(secondNumber>=0 && secondNumber<=9)
     {
      pinNumber*=10;
      pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
     }

     digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

     // build string that is send back to device that is requesting pin toggle
     String content;
     content = "Pin ";
     content += pinNumber;
     content += " is ";

     if(digitalRead(pinNumber))
     {
       content += "ON";
     }
     else
     {
       content += "OFF";
     }

     sendHTTPResponse(connectionId,content);

     // make close command
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendCommand(closeCommand,1000,DEBUG); // close connection
    }
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    int dataSize = command.length();
    char data[dataSize];
    command.toCharArray(data,dataSize);

    esp8266.write(data,dataSize); // send the read character to the esp8266
    if(debug)
    {
      Serial.println("\r\n====== HTTP Response From Arduino ======");
      Serial.write(data,dataSize);
      Serial.println("\r\n========================================");
    }

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{

     // build HTTP response
     String httpResponse;
     String httpHeader;
     // HTTP Header
     httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
     httpHeader += "Content-Length: ";
     httpHeader += content.length();
     httpHeader += "\r\n";
     httpHeader +="Connection: close\r\n\r\n";
     httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
     sendCIPData(connectionId,httpResponse);
}

/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(int connectionId, String data)
{
   String cipSend = "AT+CIPSEND=";
   cipSend += connectionId;
   cipSend += ",";
   cipSend +=data.length();
   cipSend +="\r\n";
   sendCommand(cipSend,1000,DEBUG);
   sendData(data,1000,DEBUG);
}

/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
    String response = "";

    esp8266.print(command); // send the read character to the esp8266

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

but i always recieve the following error
Arduino: 1.6.12 (Windows 7), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

Sketch uses 228,949 bytes (52%) of program storage space. Maximum is 434,160 bytes.
Global variables use 32,796 bytes (40%) of dynamic memory, leaving 49,124 bytes for local variables. Maximum is 81,920 bytes.
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

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

any idea where i went wrong ?

It looks you may have badly configured your Arduino IDE: you wrote a sketch for Arduino MEGA, but the console output you show looks as if you want to upload it to the ESP8266. That sounds weird. Please show us your IDE configuration (target board) for MEGA upload.

Do not use SoftwareSerial on a hardware serial port. It is pointless.
Do use a voltage divider to convert the Arduino's 5V TX to the required 3.3V the ESP8266 needs.
Do not try and program the Arduino as if it were an ESP8266 - it won't work.

I think you are getting a little confused here...

thanks! what should i edit ? it already has a 3.3 output. i changed the board to MEGA 2560 i don`t receive this error but i get some warnings and still not working

how do you know its 3.3V. there are high odds that you might have fried you esp

Connect your ESP directly to your PC. Test AT commands first. They will tell you if your good to go or not. Just open your serial monitor and set the baud rate to 115200. Select carriage return and type in AT. If it responds OK. Then your code is the problem. If it doesn't return OK, then your ESP or circuit is the problem.

thanks! but i cant connect esp directly to my PC. is there any way around this so i can test it with this setup'

do youn have an FTDI breakout?

sorry i don't have it . thats why i can't connect it. if its the only way i can order it. but is there any other way?

I would say that depends a lot on whether or not your ESP8266 is pre-loaded with the Espressif AT firmware. Flashing an ESP from a Arduino/MEGA is probably hard, if not impossible. If it is pre-loaded, it should respond to AT commands. As an in-between test, set the baudrate to 74880, and see if you get anything from the ESP when it's turned on, the ESP bootloader always prints info on the serial port at 74880 baud when turned on.


text:
The best signal source for a path-finding robot
Newbe question - I'm thinking of creating a simple robot that heads to a signal source.
Ie, when you press a button on some remote control - the robot will head towards its source.
What would be the best choice of signal? A strength of a wifi, sound?
AD

Will it have line-of-sight to the remote control? If so infrared (IR) would be my choice. You would have to place IR receivers all around the robot.

I like @Canadiancyborg's IR solution, but the same theory can be applied to any other emitter, and RF emitters may be preferable to an IR emitter since IR light can be blocked by intermediate objects. Also an omnidirectional RF transmitter is easier to arrange than an omnidirectional IR transmitter.
The basic theory is that you need to work out which direction a signal is coming from. In order to do that you need to "look around you" and find at which angle the signal is strongest.
A highly directional receiver (parabolic dish, IR receiver with lens, etc) will allow you to sense the signal strongest when the receiver is pointing directly at the source. By then rotating the receiver (either on its own independent rotational system, such as a servo motor, or by rotating the entire robot using the wheels) you can "lock on" to the direction where the signal is strongest and drive towards it.

Well RF is a little too powerful. My idea was to isolate the ir in something like a PVC pipe so it would detect the IR signal only at a specific angle. Otherwise, you can't really know where the target is.

@canadiancyborg RF doesn't need to be powerful - it all depends on the power of your transmitter, the sensitivity of your receiver, and the field of vision of your detector. Hence the parabolic dish (like a mini satellite dish). For IR you really want a lens to focus the receiver on a narrower point (the optical equivalent of a parabolic dish).

IR sensor in combination with an ultrasonic distance sensor would work great.
You can mimic a radar with an IR sensor so that it can detect from where the IR source from your remote is comming from. Then from there, process the angles and make you robot go towards it.
The ultrasonic distance sensor can be used a "fail" prevention system. In the sense that if it detects an object in front of the robot, it will stop, go around it and then continue towards the target

authors: Роман Деньгин


text:
IRemote with PulseSensor
I have a problem with these two modules. I am trying to create a pulse sensor but also want to use a remote for some further functionality (menu system).
I have the code separated into two files, one for the main menu and the other for the pulse sensor. They work as expected individually but when i combine the code it only displays the pulse readings and doesnt allow me to use the main menu functionality.
ISR(TIMER2_COMPA_vect) {                        // triggered when Timer2 counts to 124
  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // keep track of the time in mS with this variable
  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise

  //  find the peak and trough of the pulse wave
  if (Signal < thresh && N > (IBI / 5) * 3) { // avoid dichrotic noise by waiting 3/5 of last IBI
    if (Signal < T) {                       // T is the trough
      T = Signal;                         // keep track of lowest point in pulse wave
    }
  }

  if (Signal > thresh && Signal > P) {        // thresh condition helps avoid noise
    P = Signal;                             // P is the peak
  }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250) {                                  // avoid high frequency noise
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI / 5) * 3) ) {
      Pulse = true;                               // set the Pulse flag when we think there is a pulse
      IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
      lastBeatTime = sampleCounter;               // keep track of time for next pulse

      if (secondBeat) {                      // if this is the second beat, if secondBeat == TRUE
        secondBeat = false;                  // clear secondBeat flag
        for (int i = 0; i <= 9; i++) {       // seed the running total to get a realisitic BPM at startup
          rate[i] = IBI;
        }
      }

      if (firstBeat) {                       // if it's the first time we found a beat, if firstBeat == TRUE
        firstBeat = false;                   // clear firstBeat flag
        secondBeat = true;                   // set the second beat flag
        sei();                               // enable interrupts again
        return;                              // IBI value is unreliable so discard it
      }

      // keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // clear the runningTotal variable

      for (int i = 0; i <= 8; i++) {          // shift data in the rate array
        rate[i] = rate[i + 1];                // and drop the oldest IBI value
        runningTotal += rate[i];              // add up the 9 oldest IBI values
      }

      rate[9] = IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // add the latest IBI to runningTotal
      runningTotal /= 10;                     // average the last 10 IBI values
      BPM = 60000 / runningTotal;             // how many beats can fit into a minute? that's BPM!
      QS = true;                              // set Quantified Self flag
  // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (Signal < thresh && Pulse == true) {  // when the values are going down, the beat is over
    Pulse = false;                         // reset the Pulse flag so we can do it again
    amp = P - T;                           // get amplitude of the pulse wave
    thresh = amp / 2 + T;                  // set thresh at 50% of the amplitude
    P = thresh;                            // reset these for next time
    T = thresh;
  }

  if (N > 2500) {                          // if 2.5 seconds go by without a beat
    thresh = 512;                          // set thresh default
    P = 512;                               // set P default
    T = 512;                               // set T default
    lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
    firstBeat = true;                      // set these to avoid noise
    secondBeat = false;                    // when we get the heartbeat back
  }
  Temp = Thermistor(analogRead(tempPin));
  Sweat = analogRead(moisture);

  sei();                                   // enable interrupts when youre done!
}

I think the problem is with the actual header file. When the IRemote is initialised, it calls sei() which then turns on the global interrupts.
Is there a way to solve this issue? I was thinking about something along the lines of each interrupt should be unique and shouldnt be dependent on the other, and is there a way to tell the compiler about a hierarchy of interrupts.
Thanks in advance.

Showing only partial code is not helpful.

ISR should be as short as possible. Set flag and let the main program to handle it.
Global interrupt flag is handled automatically (on AVR platform), so you don't have to call cli().
Enabling interrupts in ISR handler might cause more problem than you can even imagine. Usual one is stack overflow caused by going deeper and deeper by another ISRs (or the same one, if it's longer than ISR period).