text:
Data is not being written into SD card
I want to save the file as date and time  and I want to open the file mySensorData = SD.open(filename, FILE_WRITE); in the set up. It shows "insert SD card" when I try to open the file in setup.
The data is not being written into the SD card. It is creating the file but not writing into file.

and the first line "Pressure, Temperature, Depth,Altitude" is in the file?

in setup you open "sensor1.txt" and in loop filename. test if (!mySensorData), not if (mySensorData==0)

Sorry! I just upload the new code.  I want to save the file as date and time .  and i want to open the file  mySensorData = SD.open(filename, FILE_WRITE); in the set up.  It shows insert SD card  when i try to open the file in setup .

You start logging set to LOW and then test if it is high, since it isn't you go to the else clause, you call exit(0) and kill your processor, hence your code never gets executed!
volatile boolean logging = LOW;

...

void loop()
{
   if(logging == HIGH) // starts low
   {
    ... // never executed
   }
   else
   {
    ... //
    exit(0); // now your Arduino is dead!
   }
}

The ellipses (...) are where i snipped your code out.
exit(0) turns off interrupts and loops forever with while(1); which has the effect of a full, power-consuming halt; exit(0) should have a sleep call in it, because what exit(...) does isn't very useful for an Arduino!

Sorry, I didn't get your answer. Would you please explain it to me .

@brar_kev I had stripped down the code to the structure so you can see; the first thing your loop does is check if (logging == HIGH) it was initialized it to LOW so flow goes to else clause, you do some stuff then you call exit(0) which halts the proccessor, the uC will not execute anymore instuctions until it is reset. so everything else never gets called.

But in the interrupts logging = ! logging .. so i'm making it low .. The code was working fine but when i added the RTC module then it stopped writing into the file. I checked when try to open the file in the set up the it shows iNSERT sd CARD AND  if i comment the open file section then it works . I'm  new to programming  and don't know how should i change it now .Thank for help

@brar_kev exit(0) disables interrupts, so your interrupt handler can't be executed either.

How should i proceed now ?  I'm stuck don't know what should i change to make it work

@brar_kev sorry if it wasn't obvious, but remove the exit(0) and see how it works then.

I removed that one and it still printing Insert SD card .

do the samples work? also SD.begin(4) should only be called once; remove it from the while loop in setup

I tried the Sd examples and they are working perfectly fine. I removed the SD.begin from while loop and it's still showing Insert Sd card. Thank you so much for help.

Anybody knows .. What should i do ?? I'm stuck

@brar_kev start with the sample, and add pieces to it until it works or something breaks, whatever breaks may tell you what is broken, or a better question to ask

The problem was related to memory . So i commented some Serial.print commands and then it worked perfectly fine . I edit this part  of my code .
else
   {
//    Serial.print(mySensorData);
//    Serial.println("Insert SD card for logging");
    digitalWrite(led_pin, LOW);
    lcd.clear();
    lcd.print("Insert SD card");
    delay(1000);
//
   }

Please list the lines that you had to comment out. Your answer may help someone with the same problem.


text:
Arduino loses communication with bluetooth when sending commands to nodemcu esp8266
i've been working on a project using an Arduino UNO, Bluetooth Module HC-06 and NodeMCU esp8266, the project consists on turning leds on via bluetooth and telling the esp8266 that the leds were turned ON, so then we can display some particular webpage data, everything that is not related to the serial communication works perfectly fine.
#include <NewPing.h>
#include <Servo.h>
#include <SoftwareSerial.h>
#define TRIGGER_PIN 2
#define ECHO_PIN 3
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

SoftwareSerial Serial1(5, 4);

Servo myservo;

int ledazul = 8; // LED RED
int scLed1 = 9; // LED 1
int scLed2 = 10; // LED 2
int scLed3 = 11; // LED 3
int scLed4 = 12; // LED 4
int scLed5 = 13;
int fan = 6;
bool br = false;
bool bra = false;
bool porta = false;
int pos = 0;

char val;
void setup() {

  Serial1.begin(115200);
  Serial.begin(9600);
  myservo.attach(7);
  pinMode(ledazul, OUTPUT);
  pinMode(scLed1, OUTPUT);
  pinMode(scLed2, OUTPUT);
  pinMode(scLed3, OUTPUT);
  pinMode(scLed4, OUTPUT);
  pinMode(scLed5, OUTPUT);
  pinMode(fan, OUTPUT);

}
void loop() {
  if (Serial.available() > 0)
  {
    val = Serial.read();

    Serial.print("Ping: ");
    int dist = sonar.ping();
    Serial.print(sonar.convert_cm(dist));
    Serial.println("cm");

  } else {
    //Serial.println("");
  }
  bool ledState = false;

  if (val == '1' && Serial1.available() > 0)
  {

    Serial1.print(val);
    Serial.print("SENT");
  }

  if (val == '0' && Serial1.available() > 0)
  {

    Serial1.print(val);
    Serial.print("SENT");
  }

  if (val == 'A')
  {
    digitalWrite(ledazul, !digitalRead(ledazul));
    ledState = true;
  }
  if (val == 'B')
  {
    Serial.print("Ping: ");
    int dist = sonar.ping();
    Serial.print(sonar.convert_cm(dist));
    Serial.println("cm");
  }
  if (val == 'C')
  {
    digitalWrite(scLed1, HIGH);
    ledState = true;
  }
  if (val == 'D')
  {
    digitalWrite(scLed2, HIGH);
    ledState = true;
  }
  if (val == 'E')
  {
    digitalWrite(scLed3, HIGH);
    ledState = true;
  }
  if (val == 'F')
  {
    digitalWrite(scLed4, HIGH);
    ledState = true;
  }

  if (val == 'G')
  {
    digitalWrite(scLed5, HIGH);
  }
  if (val == 'S')
  {
    digitalWrite(fan, HIGH);
  }
  if (val == 'O')
  {
    switch (porta)
    {
        if (pos < 90)
        {
        case false:
          porta = true;
          for (int x = 0; x < 90; x++)
          {
            myservo.write(x);
            delay(15);
          }
        }
        break;
    }
  }
  if (val == 'P')
  {
    switch (porta)
    {
        if (pos >= 90)
        {
        case true:
          porta = false;
          for (int y = 90; y > 0; y--)
          {
            myservo.write(y);
            delay(15);
          }
        }
        break;
    }
  }
}

What happens is, i can toggle ESP led on or off as long as i dont use commands that uses bluetooth module, it works perfectly fine. Now, if i do use bluetooth commands and then esp commands, it'll lose connection with the bluetooth module.
What im looking for is a workaround for the baudrates, because i have a 9600baudrate for the HC-06 and 115200 for the nodemcu, how do i do to fix it?

You have a copy paste error in the code (nested setup functions). Also I don't really understand the code. With which Serial you connect the HC-06? And what does "it does not work" mean?what are you expecting as output?

Hello Chrisl, There arent any errors with the code. HC-06 is connected to pin 0 and 1 respectively on arduino, and esp8266 is connected to 5 and 4 of the arduino using SoftwareSerial, My problem is that, whenever i send a message to ESP8266 it loses bluetooth connection, i can no longer trigger bluetooth leds, however the opposite doesnt happen. If i toggle bluetooth leds FIRST, i can still toggle esp8266 leds

Yes you have a copy paste error in the code above. Look at the two lines with void setup(). 2. Does the HC-06 lose the bluetooth connection or does the Serial code stop working? This is an important difference, because the Arduino doesn't know anything about the bluetooth connection. It only write on it's serial interface

There is only 1 part in the code, where you read anything from the ESP, but it is commented out. Even if it weren't, it would only be executed, if you first send a 0 or 1 from your bluetooth device. It is unclear, what do you want to achieve with this if-statement, and what with the following else-statement (why is it an error, if there is nothing to read in the receive buffer?) And this else-statement has a syntax error ( you must enclose both commands into the { } pair. All in all correct these errors and describe better, what you want to achieve with these parts of the code.

Hey again chrisl, i have editted the main post with the full code, 0 and 1 sends a message via serial to the ESP8266(NodeMCU), let me remind me that both communication works as long as i dont attempt another module commucation after. Hopefully it should look easier to understand now.

What is the sense in checking, if there is something to read from Serial1, but then don't reading it? Are you sure you want to include this into the if statement?

That was a maneuver to tell arduino to check if serial1 is available to receive inputs from arduino, so it didnt overlap the communication with the bluetooth, after

Let us continue this discussion in chat.

source: Stack Exchange

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

sort: votes


text:
void loop is only run once why?it can recive only off signal?
    int L1=12;
void setup() {

  Serial.begin(9600);

  pinMode(L1,OUTPUT);

}

void loop() {

char receive=Serial.read();

if(Serial.available()>0){
    receive = Serial.read();
}

{

if(receive =='A') {
  digitalWrite(L1,HIGH);
}

if(receive =='a') {
  digitalWrite(L1,LOW);
}
}
}

int L1=12;

void setup() {

  Serial.begin(9600);

  pinMode(L1,OUTPUT);

}

void loop() {

//char receive=Serial.read(); //This is incorrect. because after u perform this serial.read(), the received data in serial's buffer is cleared. So ...

if(Serial.available()>0){
    receive = Serial.read(); //... at here, your 'receive' receives nothing
}

{

if(receive =='A') {
  digitalWrite(L1,HIGH);
}

if(receive =='a') {
  digitalWrite(L1,LOW);
}
}
}

Here's the correct codes.
int L1=12;

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

void loop()
{
  char receive;

  if(Serial.available()>0)
  {
    receive = Serial.read();

    if(receive =='A')
    {
      digitalWrite(L1,HIGH);
    }

    else if(receive =='a')
    {
      digitalWrite(L1,LOW);
    }
  }
}

nice, but not solving. if he sends only one character, this changes do not change the behavior of the sketch. read returns -1 if nothing is available. if the first read returns the character then next character is not available and the received character is compared to 'A' and 'a'.

so what should i do so that every time i send a character it receive and execute the conditions

@JhonRajbongshi, the problem is not in sketch

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


text:
Resistors on LCD - does a small difference matter?
I recently have tried to connect an LCD to my Arduino Uno. The tutorial
tells me I need a 220 Ohm resistor, but the only ones I have are 330 Ohm. Does it matter?
Here's the Fritzing diagram by the way:

You can use the 330 ohm resistor. If the display's backlight is not bright enough, you could add a second 330 ohm resistor in parallel with the first one.

No, it doesn't matter. That resistor is just for the backlight LEDs. The larger the resistor the dimmer the backlight will be.  As @VE7JRO suggests, you can always put two 330Ω resistors in parallel, which will halve the resistance to 165Ω, which will give a brighter backlight.

It works! But when I power the Arduino through USB, the pixels are hard to read when looking straight in (this is not the case for when I use my battery pack with 6 x 1.2V rechargables). Maybe it's a problem similar to that in https://arduino.stackexchange.com/questions/22083/arduino-lcd-changing-contrast-only-makes-black-boxes-less-readable-i-e-less-in. Anyway, I an send you pictures if you want

Just adjust your contrast.

With the potentiometer? I've tried - I doesn't work (plus I've also tried s 330 Ohm resistor and a 470 Ohm resistor). By the way, it isn't a huge problem. I can always use the battery pack

Potentiometer adjusts contrast. Check your connection. It's pins should go to (left)Battery+, (middle)V0, (right)Battery-. This creates a voltage divider and turning it's knob changes voltage on (middle)V0 pin and it informs the LCD controller how to set the contrast. And about the resistor you can even ignore it and just connect LCD directly to Battery+.

Nope. The lcd has backlight led which needs to powered separately. More resistance, dimmer it will be. Higher voltage decreases life span of your lcd backlit.


text:
Arduino writes file to SD but not content to file
I'm using an Arduino UNO, the Extended Database Library (EDB), and an microSD Card to read/write 2 database tables. I've managed to create both ".db" files on the SD (they show up in Finder when I load the microSD directly onto my Mac).
I can also populate them with placeholder data, but this data does not seem to be actually written to the file (and thus doesn't survive reboot).
Also, trying dbFile = SD.open(db_name1, FILE_WRITE); returns false, even though the files do exist on the drive?
Here's my create code:
#include <SPI.h>
#include <SD.h>
#define SD_PIN 10  //SD read/write pin
#define TABLE_SIZE 8192  //256*32
#include "Arduino.h"
#include <EDB.h>

char* db_name1 = "/DB/SENSOR1.db";
char* db_name2 = "/DB/SENSOR2.db";
File dbFile;

struct sensorLog1 {
  unsigned int id;
  float input;
  unsigned int timestamp;
}
sensorLog1;
struct sensorLog2 {
  unsigned int id;
  float input;
  unsigned int timestamp;
}
sensorLog2;

// Setting up EDB object
inline void writer (unsigned long address, const byte* data, unsigned int recsize) {
  dbFile.seek(address);
  dbFile.write(data,recsize);
  dbFile.flush();
}
inline void reader (unsigned long address, byte* data, unsigned int recsize) {
    dbFile.seek(address);
    dbFile.read(data,recsize);
}
// Create an EDB object with the appropriate write and read handlers
EDB db(&writer, &reader);

void setup() {

  Serial.begin(9600);

  createDB(db_name1, "sensorLog1");
  createDB(db_name2, "sensorLog2");

  dbFile = SD.open(db_name1, FILE_WRITE);  // Doesn't work!
  if (!dbFile) { Serial.println("File does not exist"); }

}

void loop() {}

void createDB(char* db_name, char* table_name) {

  // create file
  dbFile = SD.open(db_name, FILE_WRITE);
  db.create(0, TABLE_SIZE, (unsigned int)sizeof(table_name));

  // populate with placeholder data
  for (unsigned int i = 1; i <= 20; i++) {
    table_name.id = i;
    table_name.input = 0;
    table_name.timestamp = 0;
    EDB_Status result = db.appendRec(EDB_REC table_name);
  }

  // check data
  Serial.println(db.count());  // returns '20'

  // close file to write
  dbFile.close();

}

does the sample work? the sample uses different code for creating and opening an existing database.

@esoterik, yes, the code works if I replace all instances of table_name in the for loop with one of the table names (e.g. sensorLog1), but then obviously the function only works for that particular table...

since your structs are identical except for the name, you should be able to do this with only one struct. sizeof doesn't do reflection, it won't do what your trying to do.

what for inline? how can you have a reference to inline function?

@Juraj, I'm not sure what you're trying to say -- that part comes straight from the EDB code (https://github.com/jwhiddon/EDB/blob/master/examples/EDB_SDCARD_Optimized/EDB_SDCARD_Optimized.ino)

db.create(0, TABLE_SIZE, (unsigned int)sizeof(table_name));

The third parameter is the record size! sizeof doesn't work on data, it works on types, so your getting the size of a char* instead of the size of your sensorlogN struct.
Your code as written shouldn't compile! a char* doesn't have a .id member.
table_name.id = i;
table_name.input = 0;
table_name.timestamp = 0;

Hmm I clearly don't have a perfect understanding of the different variable types yet... How could I make this for loop work, when the two structs are not the same size?

@user1092247 you would have to pass in the size, and a factory function pointer that would create the the correct objects for you, but I don't think that will actually help you accomplish whatever it is your trying to do.

@esoterik, add solution to the answer


text:
How to define function/macro so it is accesible throughout various cpp files
I recently came across this nice SerialPrint() implementation:
void StreamPrint_progmem(Print &out,PGM_P format,...)
{
  // program memory version of printf - copy of format string and result share a buffer
  // so as to avoid too much memory use
  char formatString[128], *ptr;
  strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem
  // null terminate - leave last char since we might need it in worst case for result's \0
  formatString[ sizeof(formatString)-2 ]='\0';
  ptr=&formatString[ strlen(formatString)+1 ]; // our result buffer...
  va_list args;
  va_start (args,format);
  vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
  va_end (args);
  formatString[ sizeof(formatString)-1 ]='\0';
  out.print(ptr);
}

#define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__)
#define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__)

I want to use it in my more complex projects to save precious RAM space.
This works really well when I have just one *.ino file where I'm using the SerialPrint() function.
When I try to use it in my more complext projects, which consist of a central *.ino files and several .cpp/.h files (mostly one cpp/h pair per class).
The problem is if I put the code below into the *.ino file, it will not be known inside any of the *.cpp files. The compiler is not complanining, but I'm never seeing the serial output of my code.
Any ideas how to fix it?
I've tried putting this code in a central global.cpp/h file which I include everywhere, but it does not seem to work (no output on serial).
Thanks in advance!-

This looks to me like an inefficient emulation of vsnprintf_P(). Also, if you want to use printf-style formatting, why not just use printf()?

@EdgarBonet: Correct me if I'm wrong but I don't think the functions you mention are availabe in the arduino IDE. The code I linked to allows use of printf() like functionality with the added extra that it puts the formatting strings in progmem, saving precious RAM in the process.

They are available. On AVR-based boards, like the Uno, the Arduino library is built atop avr-libc, and all the functionality of this library is available. The only caveat is that you have to set up stdout before using it, c.f. the documentation on stdio.h. You can have the formatting string in progmem too by using printf_P() and the other _P variants.

Have you thought of turning it into a small library?
libraries/StreamPrint/StreamPrint.cpp:
#include <StreamPrint.h>

void StreamPrint_progmem(Print &out,PGM_P format,...)
{
  // program memory version of printf - copy of format string and result share a buffer
  // so as to avoid too much memory use
  char formatString[128], *ptr;
  strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem
  // null terminate - leave last char since we might need it in worst case for result's \0
  formatString[ sizeof(formatString)-2 ]='\0';
  ptr=&formatString[ strlen(formatString)+1 ]; // our result buffer...
  va_list args;
  va_start (args,format);
  vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
  va_end (args);
  formatString[ sizeof(formatString)-1 ]='\0';
  out.print(ptr);
}

libraries/StreamPrint/StreamPrint.h:
#include <Arduino.h>

extern void StreamPrint_progmem(Print &out,PGM_P format,...);

#define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__)
#define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__)

Then in your code, wherever you want to use it:
#include <StreamPrint.h>

You can read more about writing libraries here: http://www.arduino.cc/en/Hacking/LibraryTutorial

Thanks for your answer. I tried this but got some compiler errors: StreamPrint.h:6:68: error: initializer fails to determine size of '__c' StreamPrint.h:6:68: error: array must be initialized with a brace-enclosed initializer StreamPrint.h:6:94: error: invalid initialization of non-const reference of type 'Print&' from an rvalue of type 'const char*' StreamPrint.h:3:13: error: in passing argument 1 of 'void StreamPrint_progmem(Print&, const char*, ...)'

Compiles fine for me. What are you using?

Normally visual studio 2013 with VisualMicro, but I tried in arduino IDE 1.6.1 and got the same error

It must be the code surrounding it then, since I can't get it to fail at all.  Try posting your test code.

Yep I had borked it... I started a new test sketch and suddenly everything works. Found out I had the code also still in my main *.ino file of my other big project.. Thanks for your help!

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


text:
Arduino R/C compatible transmitter and reciever
I want to make a RC buggy or something down those lines (using Legos of course) and I'm confused while looking what transmitter/receiver to use. Would like a simple classic remote and any compatible receiver for the Arduino.
Found such a remote: http://www.hobbypartz.com/79p-th9x-r9b-9channel-radio.html
But this seems way overkill for what I want to do. Any links or suggestions would be appreciated. Hope the question isn't too broad for stack exchange.

If you want really cheap you could use a old IR remote control.

The price isn't the main factor, but the one I linked is a bit too expensive. I'm guessing 20-30 euros would be good.

If you want to involve an Arduino on the receiver, you may want to choose a transmitter which is compatible with a 2.4 GHz chipset that is both available, and for which you can find Arduino code.  The NRF24L01+ and Beken compatibles are probably the most available, and a lot of RC toys use something compatible, though getting firmware right to interact with them can be tricky.  Beware that there are some other chips in wide use too, which can be harder to source a module for.
You can use an off-the-shelf multi-channel receiver, but that will tend to output each channel on a distinct PWM pin, which is annoying if you want to capture the data into an Arduino.
You might want to spend some time looking on rcgroups and in various hobby drone sites - the latter folks have a similar problem, as they want to collect all the control channels and mediate them through a custom flight computer (which in the early days was sometimes Arduino-compatible).
You can also make your own transmitter - perhaps by retrofitting an NRF24L01+ module and miniature Arduino equivalent into the casing of an older 5/72/75 MHz set - or the IR transmitter from a toy helicopter.

Thanks for the great answer! Making my own transmitter/receiver would be a no go for me as I'm not that good with electronics, so I want to buy a combo of both, then program the Arduino to (I'm a developer) drive the motors n stuff from the received sigal :) I found this: http://www.ebay.co.uk/itm/FS-GT2-2CH-2-4G-Radio-Remote-Control-Transmitter-and-Receiver-RC-Car-Boat-UK-/131121926912?pt=LH_DefaultDomain_3&hash=item1e8779d300
Seems to me, that I could easily connect the receiver to a Arduino and get the channel values?

That is a two channel radio, and unhacked will output each channel on its own wire, so your Arduino will have to time two independent PWM signals.  For only two channels that is reasonable - if you wanted 4 or more it starts to be ugly.

It depends on the number of channels you need, but you could go to HobbyKing, they offer RC remotes for down to 20$

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


text:
Multiple Buttons on Single Analog Pin and Trigger Pin Arduino Uno
I've researched how to attach multiple buttons to a single analog input using a resistor network. Instructables has a good lesson on this: http://www.instructables.com/id/How-to-access-5-buttons-through-1-Arduino-input/?ALLSTEPS
My requirement is that I need to attach an interrupt to buttons (ie the analog input) before reading the analog value, so that all the buttons can act as a trigger.
This works for voltages in the higher range, but not in the lower range (the trigger input waits for a RISING edge).
Can any one suggest a circuit that steps a >0V+ to +5V input to a +5V output so that any button push would trigger the input?
Otherwise, does anyone have other suggestions on how to use triggers for each button?

Use the analog comparator in the ATmega328P to trigger an interrupt once the input voltage rises enough to indicate a button press.
Connect the analog network to both the analog input and D6.
If your lowest analog voltage is not greater than 1.2V then apply a voltage greater than 0V but more than 40mV less than your lowest analog voltage to D7. If you have not connected the voltage then configure the comparator to use the internal bandgap reference (ACSR |= _BV(ACBG)).
Enable the comparator interrupt and capture on a rising edge (ACSR |= _BV(ACIE) | _BV(ACIS1) | _BV(ACIS0)).
Disable the digital input on D6 (AIN0), and on D7 (AIN1) if connected to a voltage reference (DIDR1 |= _BV(AIN0D), DIDR1 |= _BV(AIN1D)).
Write an ISR that does what you want on comparator trigger (ISR(ANALOG_COMP_vect) { ... }).
Now go back and read all that three more times until you understand it. As always, see the ATmega328P datasheet for details.

Cool. I learned something new today. (Voted). I did not know that ATMega chips include an analog comparator, much less that you can trigger an interrupt based on comparator results. I would have built something using an op-amp, but I like the software-only solution. It looks like the ATMega2560 has the same feature. Cool! (I guess I said that...)

Do you have any links to sample sketches using the analog comparator, particularly using it as an interrupt? The registers and configuration on the AVR family are a little quirky and I find a working example very helpful in understanding how to use them. (I'm an old assembler jockey, so I'm pretty good at this stuff.)

Nope. But there is AVR128.

That'll do nicely. I didn't know that the ACI flag was set when an interrupt condition was met, even if interrupts are disabled. That's very cool, and useful for writing a tight polling loop rather than an ISR.

I re-read this 10 times and I still don't understand it...

http://en.wikipedia.org/wiki/Comparator

Considering the fact that from a functional point of view, you just want to have more digital inputs, I would propose to use a Parallel-In Serial-Out Expander, (e.g. CD4021B or 74HC165).
This IC (i.e. 74HC165) has 8 digital inputs, that can be 'shifted' and send to your Arduino using just 2 wires. Arduino has a built-in function for this (i.e. shiftIn) to read the input and to convert it to a byte.
If 8 inputs is not enough, then you can chain multiple IC to create 16, 24 ... digital inputs.
There is an official tutorial for the CD4021B.
I don't know if this is a requirement, but if you want to register multiple key-presses at the same time, then this is a really good strategy.


text:
Best way to process data received by EthernetServer
I have a program where the Arduino acts as an Ethernet Server.
The client continuously sends packets which is of the following format
Start Byte=0x7E;
Some Data/Command Bytes;      //Can be of varying length
End Byte=0x7A;

Some packets take more time to process than others.
So my question is what is the best way to read the bytes of the memory so that we always work on one packet at a time.I can read in data from the buffer one at a time and loop through till the END BYTE is reached but it doesn't seem a very efficient way to get the packets.
I would be interested if someone has better ideas on how to read in packets one at a time from the buffer in the most efficient way possible.

An important question would be if your can be sure that a packet contains exactly one message starting from the packet start - with TCP you almost certainly can't unless the sender is atypical, but with some other schemes you could.  If you can't, you will likely either need to process messages character-by-character with a state machine that can pause and continue when another packet is received, or else copy from packet(s) to a message buffer, and be able to handle a message fragmented across packets, a packet that contains the end of one message and the start of another, etc.

can you elaborate on those schemes or point me in the right direction.Thanks.


text:
Using the SD library with the ESP8266 DevKit
The situation is as follows, I've connected a SPI TFT screen to the ESP8266 DevKit, set my own MISO,MOSI, CD, SCK pins and it works fine, wanted to do the same for using the SD card reader, but then I realized that the SD library is using the pre-defined pins with no visible way override this.. There must be a way, no?
I did try editing the pins_xxx files:
static const uint8_t SS   = 10;
static const uint8_t MOSI = D7; //11;
static const uint8_t MISO = D5; //12;
static const uint8_t SCK  = D6; //13;

But it did not work, I'm not that well familiar about the build process..
So, is there a way to accomplish this? Maybe a different library?
P.S. I am using the Arduino IDE for the ESP.

Do you have a reason to not share the SCK, MISO, MOSI lines between the two devices?

on nodeMCUs, you really want to use the native (SPECIAL) pin modes when you can, especially on a device like a screen. in other words, get the SD working, then share with the TFT sans CS, which remaps.

@JamesWaldby-jwpat7 & dandavis I just got familiar with the SPI interface and did not know about sharing the pins, now I do though, thanks!

After some trial and error got both the screen and sd card reader working sharing the MISO and SCK lines.
I was using a display wit the Adafruit ST7735 driver (and their library), worked fine with both hardware and software, but the SD card reader (generic, not even a part number on it) was able to work only with hardware SPI as the standard SD library does not support software SPI for some reason.
The most important takeaway is this: The SD library internally uses the predefined MOSI,MISO and SCK pins, but fot the ESP8266 dev kit they were mapped to pins labeled HMOSI, HMISO and HSCLK - D7, D6 and D5. Now that I think about it, the H must stand for "Hardware", if only I had this epiphany sooner.


text:
mcufriend SPI connection
Bought a cheap LCD form china (mcufriend, pictured below) and I cant understand which pin is which to use it with the SPI interface (starting to get worried that I can't use it), I've figured out this much:

LCD_RST; reset pin
LCD_CS; chip select
LCD_RS;
LCD_WR;
LCD_RD;

Which of those is MOSI, SCK, DC? Trying to use it with a ESP8266 (ESP-12).

You can't use that TFT screen with SPI. The SPI interface (SD_DI, SD_DO, SC_SCK and SD_SS) is for the SD card slot only.
All the pins starting LCD_ are the 8-bit parallel ("8080" style) interface for controlling the TFT screen.


text:
How precise can I get Arduino using rotary encoders?
Stepper motors are often pricey for a large motor. However, with a powerful, standard DC motor and a rotary encoder, you can "simulate" a stepper motor. How accurate are rotary encoders with Arduino just with a basic loop and not much other code? Is it going to "miss a pulse" and not record enough rotation often? How can I handle this with much more code? Is there a better way to do this? Would interrupts help? Is there some sort of circuit that would help with this problem?
Note: It will probably not exceed 4 rotations a second... (That may be a lot but if you're doing a lead screw type mechanism that would only be 24 inches a minute if there is 10 rotations per inch of linear motion.)

I've used rotary encoders that refused to work properly when spinned fast. I guess it varies with price.

Interrupts are what you would use in this situation.
The rates that you have mentioned are slow enough where you probably would be able to count it inside of a loop, however this is not recommended, as a typical loop will take many clock cycles to complete, and depending on the number of instuctiuons per loop, you may miss some counts.
Interrupts are made for this purpose, as they can be triggered at any time, regardless of the state of the loop.
There is a function named attachInterrupt() which will take three arguments.

Interrupt Pin
Interrupt Service Routine
Mode

Below is an example for counting an interrupt
volatile int myCounter = 0;

void setup(){
    attachInterrupt(0, count, RISING);
}

void count(){
    myCounter++;
}

The Modes are as follows:

LOW, CHANGE, RISING, FALLING

More information about using interrupts can be found here.
Depending on the encoder you use, you will need to tailor the code your needs, and do some more calculations to determine your position, but this should be a good starting point.
Edit
Here is some example code from Arduino Sandbox for using a rotary encoder.

An interrupt driven edge detector on a Duemilanove easily handles 100 edges per second (6500rpm on a motor).

@WayfaringStranger So then there's no problem on an Uno, then. Thanks!

@AnnonomusPerson - How much work are you willing to put in? If you go naked (ISR_NAKED()), you can skip the automatic C context saving, and pull off 100-500 Khz interrupt rates without issue, but you're basically writing assembly in C at that point.

If you want a completely banannas document about optimizing the absolute crap out of interrupt response, look here. Placing code directly in the interrupt table to further reduce interrupt latency!

Also, note that if you're going for low-latency interrupts, the arduino attachInterrupt function injects a whole additional function-call overhead versus using the interrupt ISR() directly.

Really, though, if you want low-latency anything, you shouldn't be using arduino anything anyways.

Adding some references to already-written libraries and examples, to enable comparison between different approaches, and experiences with speed versus susceptibility to missing steps.
Reading rotary encoders:
http://playground.arduino.cc/Main/RotaryEncoders
Quadrature Encoder too Fast for Arduino (with Solution): http://www.hessmer.org/blog/2011/01/30/quadrature-encoder-too-fast-for-arduino/
Teensy Encoder library: https://www.pjrc.com/teensy/td_libs_Encoder.html
Reading rotary encoder on Arduino:
http://www.circuitsathome.com/mcu/reading-rotary-encoder-on-arduino/


text:
Are there different revisions of Arduino Uno SMD?
I know there are different revisions of the Arduino Uno itself, but are there any revisions of the SMD? If they are is SMD R2 identical to through-hole R2? I have a board marked R2 SMD and I am wondering if that is the only version that they produced in SMD format and just are signifying that it is compatible with the standard R2.

I have a R3 SMD uno, if that helps

@TheDoctor I don't think there is an R3 SMD. The R2, R3 are for the DIP boards. The only SMD board is the "Uno SMD"

@sachleen -  Yep i do - see my answer below

The only difference with the SMD Uno is the fact you can't remove the chip. There are also 2 extra analog comparators not connected to anything.
The SMD boards are compatible with the thru-hole boards, but they have SMD components, which apparently make them easier to make and cheaper. As I said before, the two extra analog inputs (A7 and A6) are left unconnected on the official boards.
Here is my Uno R3:


text:
Cannot control servo with button.
I am unable to get a button on my arduino board to control a servo. I'd like the servo to rotate 90 degrees on button push, but it is unresponsive.
Is there a flaw in my code or is it wiring?
#include <Servo.h>  // servo library

const int button1Pin = 2;  // pushbutton 1 pin
Servo servo1; // servo control object

void setup()
{
  pinMode(button1Pin, INPUT);
  servo1.attach(9);

  // Set servo 1 to output?
}

void loop()
{
  int button1State;
int position;

button1State = digitalRead(button1Pin);

if (button1State == LOW);
{
  servo1.write(90);  // move servo
}

}

It might already start at 90 degrees. If you can, turn the motor (carefully!) and see if that helps.

The problem is that servo1.write(90) does not do what you think it does.
servo.write(angle) tells the servo to go to that position, not to move by that many degrees. What you need is to set one angle when the button is not pressed, and a different angle when the button is pressed.
Normal hobby servos can move about 180 degrees. Where 0 is depends on how the servo horn is positioned. Which direction of rotation is positive depends on the manufacturer.
try something like this to set one position when the button is pressed and a different one when it is not:
if (button1State == LOW);{
    servo1.write(45);  // move servo
}
else {
    servo1.write(135);
}


text:
Does the map() function works on an ATtiny85?
I have a working project on Arduino Uno.Now I want to shrink my project using an ATtiny85. Before purchasing an waiting for the shipment to arrive, I want to make sure that my whole code will run on ATtiny85.
specialy, will the map() function which is working on  an Arduino Uno ( ATMEGA328P-PU ),  work with a ATtiny85 Microcontroller?

You don't need to have the hardware in hand to try building code for it.

The map function uses integer arithmetic, and since the ATmega series and the ATtiny series use the same 8-bit AVR instruction set, there should be no difference when using it, and you are good to go from that aspect.
Consider that there are many other differences regarding I/O pins, storage etc. - that you might want to consider. Here is a good source for a basic comparison between the ATmega based Arduino to ATtiny85.

Here is the code that implements the map function


text:
How can a USB keyboard emulator (TrinketKeyboard) type Unicode characters?
I've got an Adafruit Trinket microcontroller set up using this USB keyboard tutorial, and it works great.
I'd like to set up my project to type a shruggie ( ¯\_(ツ)_/¯ ) when I press a hardware button.
My naive solution was:
TrinketKeyboard.print("¯\_(ツ)_/¯");

But that only printed the underscores, parentheses and slashes, not the "hands" or the "face."
Is there a standard keyboard input method I could use so this device, when plugged into any Mac, will type out a string that includes Unicode (specifically Katakana) characters?
An ideal solution does not require configuring the machine before plugging this widget in, and doesn't require changing state on the machine -- although I'll take what I can get! :) (e.g., configuring Japanese keyboard support and toggling input source -- all of which is done blind since the computer can't give feedback to a lowly keyboard -- is un-ideal.)

Doesn't seem to be possible without the Unicode hex input setting.

It depends entirely on the operating system you are working with. The Arduino is merely a keyboard. It sends keystrokes. Whatever keystrokes your operating system will accept to generate unicode character are the keystrokes you have to program the Arduino to send. Most likely there is some combination of ALT-GR + keypad numbers that will do the trick.
For OS X it looks like the only possible way is to change the input settings on the computer to allow "Unicode HEX" entry.

https://discussions.apple.com/thread/1899290?tstart=0

There is no other way of doing it. As I say, the Arduino is just a keyboard. It is subject to the same rules as any other keyboard. You can only type things that can be typed. If you need to type other things the OS has to be made aware that you want to type those things through settings.

OP specifically mentions MacOS

Then it's anyone's guess what the keyboard combinations required might be then. Maybe something with the apple key (which is the same as the windows key). Either way the answer still stands - you have to find out the correct key sequences and send them as individual sequences.

If that involves making a change to the settings on the OS then that is what you have to do. There is no "magic wand" to type something that cannot be typed.

You could hack it.

Make it press CMD+SPACE
type terminal.app
press ENTER
type  echo -e
"\xC2\xAF\\_(\xE3\x83\x84)_/\xC2\xAF" | pbcopy
press ENTER
press CMD+Q
press CMD+V

though the user would see a terminal window for a second.

That's just plain nasty...

@majenko ¯_(ツ)_/¯

He has a broken arm... ):

@majenko I did copy paste it. If I try to edit the comment it's still there. So SO is doing something weird. Extra nastiness for free. (-:


text:
Arduino Pro Mini (5V) Raw Pin and VCC Pin
I am new to the microcontroller world and circuits, so bare with me. I recently bought some 5V arduino pro mini microcontrollers. I have been playing with them and they work fine, I have been powering it from an usb connection.
Now I want to power the board using a 9V battery, I connected the + to the RAW pin and the Ground to the Ground pin on the Arduino.
My question is if I can still use the VCC pins? I understand the board has a voltage regulator that from my understanding it brings down the 9V to 5V. I thought this 5 volts were available through the VCC pin but I connected an LED to it and nothing happens.

I have tried this method with an arduino Uno and it works so I dont know why it doesnt work with the Pro Mini.

Is the LED plugged in the right way? If the board is okay, it should work AFAIK.

Yes. I tried this setup with the Arduino Uno and it works

I bet it is a hardware issue if you are 100% sure it is plugged in the right way. Can you blink pin 13?... you might just have to get a replacement. I'm not sure though...

Yes i think its a defective board

Hmm... double check everything again. If it is defective, we can't really help you; you will have to contact the seller. I have no more advice, but good luck :)

You could always test it with a voltimeter to make sure it's the pin, not the power source or led where the issue lies.

Note you should have a current limiting resistor. The regulator can supply up to 150mA. With out a limit can pop your LED. Assuming it is running 5V.

Is your Mini really 5V. If it was 3V some LED's may not work, with or without limiting resistor.

As others have pointed out, without a current limiting resistor you may have fried the LED. Thus you might need another LED to test with. On a typical LED with a 1.2 forward voltage drop, a 220 ohm resistor will limit current to about 17 mA (i = v/r.)
forward voltage = supply voltage - LED voltage drop
forward voltage  = (5.0 - 1.2) = 3.8
current = 3.8V/220ohms = 17 mA.
Check the specs on your LEDs. 1.2 V forward voltage drop is common on little LEDs. Max current of 20 mA is common as well, but it doesn't pay to go all the way to the max. That's the "do not exceed or you may destroy it" level.

One way to figure out the answer to a question like this is to go have a look at the schematic. It's not perhaps not as clear as it could be there, but the VCC output of the regulator is connected to the common VCC bus across the board that's connected to the microcontroller and the JP1 and JP7 headers.
A cheap multimeter can be handy for checking voltages, and would also be able to use it to check the continuity (while the board is unplugged from everything!) between the VCC pin and the output of the regulator.


text:
Can multiple Arduinos be connected to a single relay?
I have a 16 channel relay that will basically manage 16 different contacts. However, each channel in the relay needs to be controlled by an individual Arduino. So in total I would have 16 different Arduino boards that will each control a single channel in the relay. Is this possible? If so, how do I make the conenctions?
 I tried it earlier using several arduinos and connecting their ground wires together but did not seem to work, the relays remained energized. I am using the SAINSMART 16-Channel 12V Relay Module

That board is intended to allow one micro-controller to control 16 relays. Why not get 16 single relay boards for your 16 arduino's? Also, having a common ground, plus connecting each arduous to a different relay should have worked.

@esoterik too expensive and the parts will take longer to arrive. What do I connect to the 5V input though? A separate power supply or can just one arduino power it?

you colud have one supply powering all the arudinos, and the board yes.

@esoterik so I have one arduino powering the relay module and hooked up to channel 1. Another arduino hooked up to channel 2. Only channel 1 seems to work. (both arduinos are grounded together)

Why do you need 16  Arduinos???

@juraj each arduino is meant to have its own IP address and will handle different things

one Arduino can handle different things

@Juraj orginally we were going to use something like the mega or something similar. However, each arduino is meant to simulate a specific site and has its specific properties. Using multiplexers or a single larger arduino was not going to simulate very well as the code would also need to be switching between different states. Our only possible setup is using 16 arduinos

Looking at the schematic, here are some points to be kept in mind when using this relay board:

The relay board should be powered through the 12V connector
The relay board has its own 5V regulator
The optocouplers are attached in "reverse"

So, the external connections should be

Connect all the arduino grounds together, and connect them to the board ground
Do not connect any +5V wire together
Connect arduino 1 to IN1, arduino 2 to IN2 and so on
Writing a HIGH value on the INx pin will result in the relay to be de-energized (so contact goes in NC position), writing a LOW value on INx pin energizes the relay (so contact goes in NO position)

If making this connection the board does not work as expected, try to detach all the arduino boards and manually shorting IN1 and +5V, IN1 and GND, IN2 and +5V, ...

You wrote that joining Arduino ground together didn't work.
This leads me to believe that you didn't do the most important connection. You need to have each Arduino ground connected to the Relay Module ground. Usually this requirement is fulfilled, because people power all devices from the same power supply.
Without that Relay Module inputs are "floating", and their states are random.

the relay's ground is also connected to all of the arduino's ground

and is there one 5 V power source?

each arduino has its own power source, and the module has a dedicated 12V power supply

You could think of using 16 Arduino's sending messages (or a control signal) to a Master Arduino which controls the 16 relays.
You can use a protocol (like ModBus, I2C). Or you can connect each Arduino to a dedicated input pin of a 16:1 Multiplexer and let the Master check all 16 lines one by one to check which relay need to be enabled.
This way you can even add more intelligent logic in the Master if needed.


text:
Adafruit Feather M0 Basic Proto doesn't show up
I bought a Feather M0 basic from Amazon here. I installed all the board definitions and stuff from here I restarted the IDE and when I plugged it in, the Feather doesn't show up in ports or device manager. I am using a data cable that I verified. Debug is off and USB stack is Arduino.
I also tried following the instructions here but it didn't work.
When I double-clicked the reset button, the red LED didn't pulse.
Is there anything that am I missing?
Edit: Feather is supplying 3~ volts. USB is supplying 4.5~ volts.
Edit 2: Charing LED lights up when li-poly is plugged in.

it could be that you are missing the bootloader. I don't see SWD pins on this board. that would be the way to flash a bootloader. return it

there are swdio and swclk pads on the bottom of the feather.

ok. do you have a programmer or other SAMD board?

if it is possible to use an external programmer for the feather, i'll go for it.

it must support SWD

could i use an arduino uno as isp?

Let us continue this discussion in chat.

Why would you buy from that seller? The picture for the sale is for a mattress! What makes you think they have even the slightest clue what they are doing?

They changed the picture after I bought it


text:
Servo can be moved only in steps of couple degree
I have Feetech FS5323M servo, with Sweep example code from Arduino site, it works fine, it rotates from 0 to 180 degree and back as expected.
The problem comes when I try to set servo position. I've added a simple servo.write(90); in setup, to reset servo position, but it didn't work (writeMicroseconds(1500); also failed).
After digging a little bit, I've discovered that I can rotate the servo only by a couple of degrees from its current physical position.
If the servo is at 140 degrees, I can move it back and forth only up to 7 degrees, value bigger than this will result in servo staying at its current position. So if I want to move it to 180 degrees I have to make a loop and go to this position in steps of 1-7 degrees (with delay = 15 * degree).
I attached external 2A power to the circuit and connected the grounds. It didn't solve the problem. The circuit is very simple, just servo connected to pin 3, without anything else. I also tried to add a 300uF capacitor between power and ground.
Edit 1:
I've tested pin 9 and 10 and the same happens. Sadly I have no way to test it on any other board because I have only one, same goes for the servo. I uploaded sweep example with the step size of 10, the servo didn't move or even twitched. I tried it both with a delay of 15 as well as 150.
Edit 2:
I've tested the program with only one servo.write(90); statement, but the issue hasn't been resolved. I tried it in setup and later in loop, in both programs there was only one write statement.

Quite interesting, does it happen on multiple Arduino boards (or other pins?) and does it happen on other servo's (of same and different type) as well?

start with the sweep example ..... modify the step size to 10 and upload  the new code ..... does it still fail?

The problem comes when I try to set servo position. I've added a
  simple servo.write(90); in setup, to reset servo position, but it
  didn't work

Understand that the method "setup()" in the Arduino paradigm is only run once after power up or reset.  Any code in "setup()" which positions the servo will immediately get over written by the code that positions the servo in the "loop()" method.  Likely this happens so quickly that the servo will not even react to the line "servo.write(90);".

Your servo should be powered separately from the Arduino as it draws 150mA just running and its stall current is well over an amp, according to the specs on this page. If you're powering it from the Arduino, it is quite likely that it drags the Arduino's supply voltage down enough to shut down the processor, but you may be getting away with it for very short moves.


text:
Black boxes are appearing on the second row of my LCD
the black boxes on the LCD are only on both rows and appear only when I attach the heart rate sensor to my body and blink with a delay of about 2 seconds and my contrast and wiring are perfect, the backlight of my LCD is on...
but when I attach the heart rate sensor they repeat for four or five seconds and the black boxes too would disappear leaving behind only the backlight on...

but then why do the black boxes appear???
please help me out
this is the code, schematics, and a picture of how it looks like.
    #include <LiquidCrystal.h>
#define IN1  8
#define IN2  9
#define IN3  10
#define IN4  7
int Steps = 4096; //4096 or 768
int cstep = 10;
const int rs = 7, en = 8, d4 = 3, d5 = 4, d6 = 5, d7 = 6;
const int buzzer = 2;
LiquidCrystal lcd(7, 8, 3, 4, 5, 6);

int pulsePin = A3;                 // Pulse Sensor purple wire connected to analog pin A0
int blinkPin = 13;                // pin to blink led at each beat
// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse

volatile int rate[10];                      // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;          // used to determine pulse timing
volatile unsigned long lastBeatTime = 0;           // used to find IBI
volatile int P = 512;                      // used to find peak in pulse wave, seeded
volatile int T = 512;                     // used to find trough in pulse wave, seeded
volatile int thresh = 525;                // used to find instant moment of heart beat, seeded
volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

void setup()
{
   pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
   pinMode(buzzer,OUTPUT);
  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
  Serial.begin(115200);             // we agree to talk fast!
  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
                                    // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,
                                    // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN
                                    //   analogReference(EXTERNAL);
 lcd.begin(16, 2);
 lcd.clear();
}

//  Where the Magic Happens
void loop()
{
   serialOutput();
    lcd.print("DEVICE-STATE");
     lcd.setCursor(1,1);
     lcd.print("UPDATING... ");
     lcd.setCursor(5,1);
     delay(3000);
     lcd.clear();
  if (QS == true) // A Heartbeat Was Found
    {
      // BPM and IBI have been Determined
      // Quantified Self "QS" true when arduino finds a heartbeat
      serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
      QS = false; // reset the Quantified Self flag for next time
      state();
      buzer();
      inject();
    }

  delay(20); //  take a break
}

void interruptSetup()
{
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

void serialOutput()
{   // Decide How To Output Serial.
 if (serialVisual == true)
  {
     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
  }
 else
  {
      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
   }
}

//Heart Attack Preventer

void serialOutputWhenBeatHappens()
{
 if (serialVisual == true) //  Code to Make the Serial Monitor Visualizer Work
   {
     Serial.print(" Heart-Beat Found ");  //ASCII Art Madness
     Serial.print("BPM: ");
     Serial.println(BPM);
     lcd.print("Heart-Beat Found ");
     lcd.setCursor(1,1);
     lcd.print("BPM: ");
     lcd.setCursor(5,1);
     lcd.print(BPM);
     delay(3000);
     lcd.clear();
   }
 else
   {
     sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
     sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
   }
}

void arduinoSerialMonitorVisual(char symbol, int data )
{
  const int sensorMin = 0;      // sensor minimum, discovered through experiment
  const int sensorMax = 1024;    // sensor maximum, discovered through experiment
  int sensorReading = data; // map the sensor range to a range of 12 options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
  // do something different depending on the
  // range value:
}

void sendDataToSerial(char symbol, int data )
{
   Serial.print(symbol);
   Serial.println(data);
}

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
        digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED
        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
        }

//Heart Attack Preventer
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
      digitalWrite(blinkPin,LOW);            // turn off pin 13 LED
      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
    }

  sei();                                   // enable interrupts when youre done!
}// end isr
void buzer(){
  // dangerous situation or pressed button
  if (BPM < 60 )
   {
     lcd.print("hypotension");
     lcd.setCursor(1,1);
     lcd.print("BPM: ");
     lcd.setCursor(5,1);
     lcd.print(BPM);
     delay(3000);
     lcd.clear();
   digitalWrite(buzzer,HIGH);
    delay(500);
   digitalWrite(buzzer,LOW);
    delay(500);

}

}
void inject()
{
   if (BPM>60)
   {
     lcd.print("Hypertention");
     lcd.setCursor(1,1);
     lcd.print("BPM: ");
     lcd.setCursor(5,1);
     lcd.print(BPM);
     delay(5000);
     lcd.clear();
  for(int x=0;x<Steps;x++)
  {
   switch(cstep)
  {
   case 0:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, HIGH);
   break;
   case 1:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, HIGH);
   break;
   case 2:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);
   break;
   case 3:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, HIGH);
     digitalWrite(IN4, LOW);
   break;
   case 4:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
   break;
   case 5:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, HIGH);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
   break;
     case 6:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
   break;
   case 7:
     digitalWrite(IN1, HIGH);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, HIGH);
   break;
   default:
     digitalWrite(IN1, LOW);
     digitalWrite(IN2, LOW);
     digitalWrite(IN3, LOW);
     digitalWrite(IN4, LOW);
   break;
  }

   cstep=cstep+1;
   if(cstep==8)
     {cstep=0;}

  delayMicroseconds(2500);

   }
}
}
void state()
{
  if (BPM > 60 & BPM < 74){
   lcd.print("VERY-GOOD");
     lcd.setCursor(1,1);
     lcd.print("BPM: ");
     lcd.setCursor(5,1);
     lcd.print(BPM);
     delay(3000);
     lcd.clear();
  }
}

Twiddle the 10K pot until the boxes disappear.

Start by commenting out code related to the heartbeat sensor and replace it by a trivial function that returns a constant result - in-range, out-of-range, whatever it takes to exercise parts of your LCD code. Then try it, with and without attaching the sensor to you. That will help find out whether you're seeing an electrical issue or a software one.

Are these black boxes real characters with all pixels on? Would you mind to add an image? You source is far too big to look for errors, please reduce it to a minimal reproduceable example.

@thebusybee I have added a picture of how it looks like....

Good. Now minimize your code, please. Don't forget to post it, then.

@thebusybee I'm not sure how to minimize the code as I'm not an expert at it... I actually took help from an external source which helped me write a code...

That's quite simple: Remove each line that is not necessary to reproduce the problem. ;-)

@thebusybee it might take a lot of time so please wait... In the meantime someone who is able to answer can please help me

Provide proper connections within your setup. Glue is NOT a good conductor, and breadbords are known for notoriously giving intermittent faults. Check what is moving when you apply presssure to your sensor, maybe use different breadboard/direct connections.  The 'boxes' are from wrong pot setup. Tweak the pot and check for results.

It was of a bad solder

I think it was because the charge of the battery was less and therefore the contrast of it was less and so I couldn't see the characters displayed...
Thanks to all those people who helped me with this problem and thanks to stack overflow
Now it is working as I used a different battery


text:
how to code LED turning signals on smart car
this question is regarding how to add turn led signals on arduino powered smart car. I have 4 leds to give turn indications on my smart car(line follower, obstacle avoider, Bluetooth mobile controlled and also IR remote controlled)
can someone help me to modify the code in such a way that I can add led turn signals?(I'm completely new to arduino)
want two front leds high at the same time when the car moves forward and when the car moves backward i need two back leds high at the same time.
i also need two right leds high at the same time when it turns right and I need two left leds high at the same time when it turns left .
this is the code
#include <IRremote.h>
#include <Servo.h>

//Pin assignments and global variables per function. Customize if needed
//*******Pin assignments Motor board and IR receiver********************
const int MotorRight1 = 7;
const int MotorRight2 = 8;
const int MotorLeft1 = 9;
const int MotorLeft2 = 10;
const int MotorRightPWM = 6;
const int MotorLeftPWM = 11;
const int irReceiverPin = A5;
const int servoPin = A4; //orange wire
int iSpeed = 255; //speed, range 0 to 255
const int LedPin=13;

//******Infrared key bindings********************************************
const long IRfront = 16730805;      //go straight: button up
const long IRback = 16718055;       //go back    : button down
const long IRturnright = 16734885;  //turn right : button right
const long IRturnleft = 16716015;   //turn left  : button left
const long IRstop = 16726215;       //stop       : button OK
const long IRcny70 = 16754775;      //CNY70 automatic mode: button EQ
const long IRAutorun = 16750695;    //Ultrasonic mode : button play/pause
//******Track following pin assignments and signals**********************
const int SensorLeft = 5;      //
const int SensorMiddle = 4 ;   //
const int SensorRight = 3;     //
IRrecv irrecv(irReceiverPin);  // IRrecv signal
decode_results infrared;       // decode result
//*******Ultrasonic pin assignments and signals**************************
const int echoPin = 12; // ultrasonic receive=echo pin
const int triggerPin = 13; // ultrasonic send=trigger pin
Servo myservo; // define myservo
const int degreesForward = 130; //nr degrees to look forward
const int degreesLeft = 60; //nr degrees to look left
const int degreesRight = 180; //nr degrees to look right
const int delay_time = 250; // servo motor delay
const int Fgo = 8; // go straight
const int Rgo = 6; // turn right
const int Lgo = 4; // turn left
const int Bgo = 2; // go back
//*****Bluetooth signals**************************************************
char val; //stores received character. Needs to be global to perform continuous movement

//*********General SETUP: activate pins***********************************
void setup() {
  //start receiving serial infor
  Serial.begin(9600);
  //motor connections
  pinMode(MotorRight1, OUTPUT);  //

  pinMode(MotorRight2, OUTPUT);  //

  pinMode(MotorLeft1,  OUTPUT);  //

  pinMode(MotorLeft2,  OUTPUT);  //
  pinMode(MotorRightPWM, OUTPUT); //enable for right side motor
  pinMode(MotorLeftPWM, OUTPUT); //enable for right side motor
  irrecv.enableIRIn();      // start infrared decode
  myservo.write(degreesForward);       // will make head look in front

  //black track following
  pinMode(SensorLeft, INPUT);
  pinMode(SensorMiddle, INPUT);
  pinMode(SensorRight, INPUT);

  //Ultra sonic
  //digitalWrite(2,HIGH); //what is this pin for?
  pinMode(echoPin, INPUT);
  pinMode(triggerPin, OUTPUT);
  myservo.attach(servoPin);
}

//**************Movement functions******************************
void advance(int d) { //go straight
  digitalWrite(MotorRight1, HIGH);
  digitalWrite(ledrightfrontindicator, HIGH);
  digitalWrite(MotorRight2, LOW);
  digitalWrite(ledrightfrontindicator, LOW);
  digitalWrite(MotorLeft1, HIGH);
  digitalWrite(ledleftfrontindicator, HIGH);
  digitalWrite(MotorLeft2, LOW);
  digitalWrite(ledleftfrontindicator, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void right(int d) { //turn right (single wheel)
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, HIGH);
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void left(int d) {//turn left(single wheel)
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, HIGH);
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void turnR(int d) {//turn right (two wheels)
  digitalWrite(MotorRight1, HIGH);
  digitalWrite(MotorRight2, LOW);
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, HIGH);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void turnL(int d) {//turn left (two wheels)
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, HIGH);
  digitalWrite(MotorLeft1, HIGH);
  digitalWrite(MotorLeft2, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void stopp(int d) { //stop
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, LOW);
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void back(int d) { //go back
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, HIGH);
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, HIGH);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}

//************Ultrasonic distance calculator*************************************
//detect distance for given angles and print char + direction
float getDistance(int degrees, char dir) {
  myservo.write(degrees);
  digitalWrite(triggerPin, LOW); // ultrasonic echo low level in 2us
  delayMicroseconds(2);
  digitalWrite(triggerPin, HIGH); // ultrasonic echo high level in 10us, at least 10us
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW); // ultgrasonic echo low level
  float distance = pulseIn(echoPin, HIGH); // read time
  distance = distance / 5.8 / 10; // turn time to distance
  Serial.print(dir); //
  Serial.print(" distance: "); //
  Serial.print(int(distance)); //  output distance (mm)
  Serial.print("\n");
  return distance;
}
//*************Ultrasonic direction decision making******************************
//measurements three angles (front, left, right
int getDirectionFromdetection() {
  int Fspeedd = 0; // front distance
  int Rspeedd = 0; // right distance
  int Lspeedd = 0; // left distance
  int delay_time = 250; //
  int directionn =0;

  //get front distance
  Fspeedd = getDistance(degreesForward, 'F');

  // if distance is less than 10mm
  if (Fspeedd < 10) {
    stopp(1); //  clear output
    directionn = Bgo;
  }
  // if distance less than 25 mm
  else if (Fspeedd < 25) {
    stopp(1); // clear output
    Lspeedd = getDistance(degreesLeft, 'L'); // detection distance on left side
    delay(delay_time); // waiting for the servo motor to become stable

    Rspeedd = getDistance(degreesRight, 'R'); // detection distance on right side
    delay(delay_time); // waiting for servo motor to be stable

    // if left distance greater than right
    if (Lspeedd > Rspeedd) {
      directionn = Lgo; // go left
    }

    if (Lspeedd <= Rspeedd) {//if left distance less than right
      directionn = Rgo; //go right
    }

    if (Lspeedd < 15 && Rspeedd < 15) { //if distance less 10mm both right and left
      directionn = Bgo; //go back
    }
  }
  else {
    directionn = Fgo; //go straight
  }
  return directionn;
}

void autoRunUsingUltraSonic() {
  bool stopPressed;
  int directionn = 0; // front=8, back=2, left=4, right=6
  while (IRAutorun) {
    myservo.write(80); // make the servo motor reset
    directionn = getDirectionFromdetection();
    stopPressed = stopCommandPressed();
    if (stopPressed) {
      break;
    }
    else if (directionn == Fgo) { //go straight
      infrared.value = 0;
      advance(5); //
      Serial.print(" Advance "); //
      Serial.print(" ");
    }
    else if (directionn == Bgo) { //go back
      infrared.value = 0;
      back(8); //
      turnL(3); //
      Serial.print(" Reverse "); //
    }
    else if (directionn == Rgo) { //turn right
      infrared.value = 0;
      back(1);
      turnR(60); //
      Serial.print(" Right "); //
    }
    else if (directionn == Lgo) { //turn left
      infrared.value = 0;
      back(1);
      turnL(60);
      Serial.print(" Left ");
    }
  }
  infrared.value = 0;
}

//*************************Bluetooth functionality***********************
//Bluetooth commands
void bluetoothCommand() {
  if (Serial.available()) { //check if bluetooth command available
    val = Serial.read();
    Serial.write(val);
  }
  if (val == 'F') { // Forward
    advance(10);
  }
  else if (val == 'S') { // Stop Forward
    stopp(10) ;
    val = Serial.read(); //read value again, otherwise can't continu with infrared
  }
  else if (val == 'B') { // Backwards
    back(10);
  }
  else if (val == 'R') { // Right
    turnL(10);
  }
  else if (val == 'L') { // Left
    turnR(10);
  }
  else if (val == 's') { // Stop, not used though
    stopp(10 ) ;
  }
  else if (int(val) >= 49 && int(val) <= 57) { //set speed
    iSpeed = (int(val)-48)*26;
    Serial.println("Speed set to: " + iSpeed);
  }
  else if (val == 'q') { //set speed
    iSpeed = 255;
    digitalWrite(LedPin,HIGH);
    Serial.println("Speed set to: " + iSpeed);
  }
  else if (val == 'W') {
    digitalWrite(LedPin,HIGH);
  }
  else if (val == 'w') {
    digitalWrite(LedPin,LOW);
  }
}

//Check if stop command on remote is pressed (button 5)
bool stopCommandPressed(){
  bool stopPressed = false;
  if (irrecv.decode(&infrared)) {
    irrecv.resume();
    Serial.println(infrared.value, HEX);
    if (infrared.value == IRstop) {
      stopp(10);
      stopPressed = true;
    }
  }
  return stopPressed;
}

void followBlackLine() {
  bool stopPressed;
  int SL;  //sensor left
  int SM;  //sensor middle
  int SR;  //sensor right
  while (IRcny70) {
    SL = digitalRead(SensorLeft);
    SM = digitalRead(SensorMiddle);
    SR = digitalRead(SensorRight);

    if (SM == HIGH) {//middle sensor in black area
      if (SL == LOW & SR == HIGH) {//left sensor in black area, right sensor in white, turn left
        left(0);
      }
      else if (SR == LOW & SL == HIGH) {//left white, right black, run right
        right(0);
      }
      else { // left and right both in white, go straight
        advance(0);
      }
    }
    // middle sensor in white area
    else {
      if (SL == LOW & SR == HIGH) { // left black ,right white, turn left
        left(0);
      }
      else if (SR == LOW & SL == HIGH) {
        right(0);
      }
      else {  //left and right both in white, stop
        stopp(0);
      }
    }
    stopPressed = stopCommandPressed();
    if (stopPressed) {
      break;
    }
  }
  infrared.value = 0;
}

//**************************************MAIN LOOP***************************************
void loop() {
  //bluetooth commands
  bluetoothCommand();
  //************************************normal remote control mode ********
  // decoding success 'receive infrared signal
  if (irrecv.decode(&infrared))  {
    if (infrared.value == IRfront) {
      advance(0); //go straigt
    }
    else if (infrared.value ==  IRback) {
      back(0); //go back
    }
    else if (infrared.value == IRturnright) {
      turnR(0); // go right
    }
    else if (infrared.value == IRturnleft) {
      turnL(0); // go left
    }
    else if (infrared.value == IRstop) {//stop
      stopp(0);
    }
    //********************follow black line********cny70 automatic mode********
    else if (infrared.value == IRcny70) {
      followBlackLine();
    }
    //***********************ultrasonic automatic mode***************************
    else if (infrared.value == IRAutorun ) {
      autoRunUsingUltraSonic();
      myservo.write(degreesForward);       // will make head look in front
    }
    //********************wait a little before continuing**************************
    irrecv.resume();
    delay(300);
  }
  else {
    stopp(0);
  }
}

This is quite a lot of code. Did you write it yourself? What exactly prevents you from adding LEDs, which you turn on and off with digitalWrite(), just like you activate the motors.

Why do you have this loop in your followBlackLine() function: while (IRcny70) ? `IRcny70 is a constant with a value greater than zero, so this is essentially an infinite loop, thats difficult to read.

The same goes for autoRunUsingUltraSonic()

I got the code online

i did not write it myself

as im a beginner please tell me what modifications i will have to do to add leds

i need 2 leds in front and 2 leds at the back of the car.

i want two front leds high at the same time when the car moves forward and when the car moves backward i need two back leds high at the same time.

i also need two right leds high at the same time when it turns right and  I need two left leds high at the same time when it turns left

So no blinking or stuff like that? Then you can simply turn on the corresponding LEDs in your moving functions ( back(), advance()) with a digitalWrite() and turn them off after the delay() with the same function. Have you looked at the many examples, that come with the Arduino IDE? They can teach you how to control LEDs right good.

please don't get angry, can you please do that for me as i tried but it didn't work...

do I have to use any resistor or something like that to make it work??

I'm not angry. But you will not get happy with the Arduino platform, if you don't try to understand, how the code actually works. And also we are not a free coding service. It is part of the working principle of this site, to first research the topic and try it out, and then come here with a specific question. One reason for this is, that you would have to answer the same questions over and over again, which already have been explained on the web for multiple times. So please first learn how basic examples like Blink work and how the components have to be connected. It's all on the web.

This site is not a free code writing service.

Like chrisl suggested, add the led code to the functions advance, back, left, and right
const int LedFrontRight = 21;//change pin numbers
const int LedFrontLeft = 22;
const int LedBackRight = 23;
const int LedBackLeft = 24;

// ...

void setup() {
  // ...
  pinMode(LedFrontRight, OUTPUT);
  pinMode(LedFrontLeft , OUTPUT);
  pinMode(LedBackRight , OUTPUT);
  pinMode(LedBackLeft  , OUTPUT);
}

//**************Movement functions******************************
void advance(int d) { //go straight
  digitalWrite(LedFrontRight, HIGH);
  digitalWrite(LedFrontLeft , HIGH);
  digitalWrite(LedBackRight , LOW);
  digitalWrite(LedBackLeft  , LOW);
  //...
}
void right(int d) { //turn right (single wheel)
  digitalWrite(LedFrontRight, HIGH);
  digitalWrite(LedFrontLeft , LOW);
  digitalWrite(LedBackRight , HIGH);
  digitalWrite(LedBackLeft  , LOW);
  //...
}
void left(int d) {//turn left(single wheel)
  digitalWrite(LedFrontRight, LOW);
  digitalWrite(LedFrontLeft , HIGH);
  digitalWrite(LedBackRight , LOW);
  digitalWrite(LedBackLeft  , HIGH);
  //...
}
void turnR(int d) {//turn right (two wheels)
  digitalWrite(LedFrontRight, HIGH);
  digitalWrite(LedFrontLeft , LOW);
  digitalWrite(LedBackRight , HIGH);
  digitalWrite(LedBackLeft  , LOW);
  //...
}
void turnL(int d) {//turn left (two wheels)
  digitalWrite(LedFrontRight, LOW);
  digitalWrite(LedFrontLeft , HIGH);
  digitalWrite(LedBackRight , LOW);
  digitalWrite(LedBackLeft  , HIGH);
  //...
}
void stopp(int d) { //stop
  digitalWrite(LedFrontRight, LOW);
  digitalWrite(LedFrontLeft , LOW);
  digitalWrite(LedBackRight , LOW);
  digitalWrite(LedBackLeft  , LOW);
  //...
}
void back(int d) { //go back
  digitalWrite(LedFrontRight, LOW);
  digitalWrite(LedFrontLeft , LOW);
  digitalWrite(LedBackRight , HIGH);
  digitalWrite(LedBackLeft  , HIGH);
  //...
}


text:
LED intensity on digital pins
I am using an Arduino UNO.
On any digital/analog pin, if an LED (with resistor) is connected and we use digitalWrite(pin,HIGH) the LED lights up rather dimly.
On the other hand, if we use pinMode(pin,OUTPUT) and then use digitalWrite, the LED lights up to maximum intensity.
I checked that in both cases, the voltage on the pin is 5V. Any explanation for this ? Thanks.

This is not a duplicate question. I am specifically asking the effect of declaring a pin as OUTPUT versus direct use of digitalWrite on the pin.

This is due to a specific feature of the AVR microcontrollers, where the
same register (PORTB, PORTC or PORTD) is used for controlling both
the output value of the pin and its optional internal pullup resistor.
The command digitalWrite(pin,HIGH) sets to 1 the bit of this register
corresponding to the selected pin.

If the pin is set to INPUT (which is the default), the effect of
digitalWrite(pin,HIGH) is to turn on the internal pullup.
If the pin is set to OUTPUT, the same command sets the output to
HIGH.

The internal pullup is about 30 kΩ, which lets flow a very small
current through the LED. You may notice that the voltage at the pin is
5 V if nothing is connected to it, but significantly less when the
LED is connected. Notice also that the preferred way of enabling the
pullup is pinMode(pin,INPUT_PULLUP).


text:
How to control the power of attiny13a via pin change interrupt?
I'm trying controll the power of attity13a and turn off/turn on the led.
I'm going to goals:
After to click on the button0
led will blicking 5 second nad then the attiny13a going to sleep.
After to click on the button1 then wake attiny13a up and then led will shane.

The button0 to sleep and blink the led.
the button1 to wake up and turn on the led.
Could you explain what is wrong in this sketch, please?
thank you for your answers.

code:
    #define F_CPU   1200000UL
    #define LED     PB2 // PB2
    #define BUTTON1 PB1 // PCINT1
    #define BUTTON0 PB0 // PCINT0

    #define HIGH         1
    #define LOW          0
    #define INPUT        0
    #define OUTPUT       1
    #define INPUT_PULLUP 2
    #define FALSE        0
    #define TRUE         1
    #define _BV(bit)    (1 << (bit))

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <avr/sleep.h>
    #include <util/delay.h>

    void pinMode(uint8_t pin, uint8_t mode)
    {
        if(mode == OUTPUT) // Pin as output
            DDRB |= _BV(pin);
        else // Pin as input or input pullup
        {
            DDRB &= ~_BV(pin); // Set pin as input
            if(mode == INPUT_PULLUP)
                PORTB |= _BV(pin); // Enable pullup resistors
        }
    }

    void digitalWrite(uint8_t pin, uint8_t val)
    {
      if(val)
        PORTB |= _BV(pin);  // Set pin high
      else
        PORTB &= ~_BV(pin); // Set pin low
    }

    uint8_t digitalRead(uint8_t pin)
    {
      return !!(PINB & _BV(pin));
    }

    // go to sleep
    ISR(PCINT0_vect)
    {
       if(digitalRead(BUTTON0)){
            int i=0;
            while(i<10){
                blink();i=i+1;
            }
            set_sleep_mode(SLEEP_MODE_PWR_DOWN);
            sleep_enable();
            sleep_cpu();
        }
    }

    //wake up
    ISR(PCINT1_vect){
       if(digitalRead(BUTTON1)){
        digitalWrite(LED, HIGH);
       }
    }

    void blink(){
        digitalWrite(LED, LOW);
        _delay_ms(500);
        digitalWrite(LED, HIGH);
        _delay_ms(500);
    }

    int main(void)
    {
        pinMode(BUTTON0, INPUT_PULLUP);
        pinMode(BUTTON1, INPUT_PULLUP);

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

        // Sets the Pin change interrupt mask PB0, PB1
        PCMSK |= _BV(PCINT0)|_BV(PCINT1);

        //Enables Interrupts globally after setup
        //sei();
        SREG |= _BV(SREG_I);

        while(TRUE){}
    }

Does the program work? If not, what is its behavior?

The led is on and nothing happens when click on the buttons

How is the LED wired?

Note that blink() lacks a delay in the HIGH state, and the tiny13 has no PCINT1_vect.

The short leg of led connected to GND.
The long leg of led connected to the resistor (1kOm) and to PB2

Updated the function of blink.

Could you explain, please, how to correctly go to power saving mode and wake attiny up from power saving mode?

You need to enable PCIE in GIMSK for PCINT interrupts to be recognised. Also all interrupts go through PCINT0_vect and you have to differentiate the pins within that.

Beside the problems stated above, your code also doesn't account for switch-bounce.

is the program actually being loaded into the attiny13a? ... are you able to run a simple program that blinks the LED?

#define F_CPU   1200000UL

#define LED     PB2 // PB2
#define BUTTON1 PB1 // INT0
#define BUTTON0 PB0 // PCINT0

#define HIGH         1
#define LOW          0
#define INPUT        0
#define OUTPUT       1
#define INPUT_PULLUP 2
#define FALSE        0
#define TRUE         1
#define _BV(bit)    (1 << (bit))

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <util/delay.h>

void pinMode(uint8_t pin, uint8_t mode){
    if(mode == OUTPUT) // Pin as output
        DDRB |= _BV(pin);
    else // Pin as input or input pullup
    {
        DDRB &= ~_BV(pin); // Set pin as input
        if(mode == INPUT_PULLUP)
            PORTB |= _BV(pin); // Enable pullup resistors
    }
}

void digitalWrite(uint8_t pin, uint8_t val){
  if(val)
    PORTB |= _BV(pin);  // Set pin high
  else
    PORTB &= ~_BV(pin); // Set pin low
}

uint8_t digitalRead(uint8_t pin){
  return !!(PINB & _BV(pin));
}

//wake up
ISR(INT0_vect){
   sleep_disable();
   //cli(); // Turn off global interrupts
   digitalWrite(LED, HIGH);
}

void blink(){
    digitalWrite(LED, LOW);
    _delay_ms(1000);
    digitalWrite(LED, HIGH);
    _delay_ms(1000);
}

// go to sleep
ISR(PCINT0_vect)
{
   //cli(); // Turn off global interrupts
   if(!digitalRead(BUTTON0)){
        cli(); // Turn off global interrupts

        blink();

        digitalWrite(LED, LOW);

        sei(); // Turn on global interrupts
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_enable();
        sleep_cpu();
    }
}

int main(void)
{
    //enabled external interrupt
    MCUCR=0;
    //MCUCR=0b00000000;
    GIMSK|=_BV(INT0); // enabled external interrupt INT0 - PB1

    // Sets the Pin change interrupt mask
    GIMSK|=_BV(PCIE);
    PCMSK|=_BV(PCINT0);//PB0

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

    pinMode(BUTTON1, INPUT_PULLUP);//INT0 - PB1
    pinMode(BUTTON0, INPUT_PULLUP);//PCINT0 - PB0

    //Enables Interrupts globally after setup
    //SREG |= _BV(SREG_I);
    sei(); // Turn on global interrupts
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_enable();
    sleep_cpu();

    while(TRUE){}

    return 0;
}


text:
Freeduino avrdude stk500_getsync() not in sync
I have a Freeduino USB 1.1 board with atmega 8l-8pu microcontroller on it. When I try to upload program, it shows error:
avrdude stk500_getsync() not in sync: resp 0x00

I have tried reset and the red led blinks which I think suggest bootloader is working fine.
On Arduino IDE, I have set Arduino Uno and correct port which is shown in device manager.
One weird problem that I noticed is that no matter which USB port I connect to, it says COM9 on device manager. Is that something to look into?
Any ideas?

Do you have anything plugged into the RX/TX pins? That has tripped me up a few times.

@Nathan nope....

There could be many reasons for the problem you have got.
1) Try to program your Board with any other device you have got. If you are trying to program it with PC try to do it using Laptop.
2) Plug your board to any other port. Then Right Click My Computer and Select Manage--> Device Manager and find the port where your Freeduino is connected. Then Select that port in  your Arduino IDE.
Solution 1 worked for me!


text:
How to read a PWM OUTPUT PIN value?
How to get a pwm pin value that is in pinMode OUTPUT?
How to get a digital OUTPUT PIN value:
#define pin 3

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

void loop()
{
    delay(1000);
    digitalWrite(pin, HIGH);
    Serial.println(bitRead(PORTD,pin));
    delay(1000);
    digitalWrite(pin, LOW);
    Serial.println(bitRead(PORTD,pin));
}

For testing reasons, I want to get PWM output pin value.
Incorrect sketch:
#define pin 3

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

void loop()
{
    delay(1000);
    analogWrite(pin, 100);
    Serial.println(pulseIn(pin, HIGH)); // value of the PWM output pin
}

This sketch was created for example only.
I don't know PWM value because PWM value will be generating dynamically.
Could you explain how to get a PWM output pin value, please?

You can't. There is no single "value" for it, it's constantly changing. You could average it through a low-pass filter and feed it back through an analog pin. Or you could connect it to an input pin and measure pulse width and frequency, but you can't do it on the pin itself. Not with normal Arduino tools. Besides, you know the value already. It's "100", since that's what you set it to. What are you actually trying to achieve?

BTW: the first sketch reads value in POTD register, not the value on the actual pin. It might be for example shorted and PIND register would read it correctly. It's possible to read the actual value (by reading PIND) but as Majenko wrote, it's changing, so you'd have to read it at constant rate or measure the low and high time. Funny, the pulseIn should be actually working as it must be using PIND internally

Maybe you would be able to get the value back by reading the corresponding Output Compare Registers of the used timer (I think, this is used for the generation, though I didn't check).

store the value to a variable. that is the right way. but if your task is to read the generated pwm on analog pin, then https://arduino.stackexchange.com/questions/55698/read-analog-port-set-as-output/55700#55700

According to the source code implementation of analogWrite function
(Arduino analogWrite source code explanation).
You can use OCRnx register for reading PWM value.

That would be OCR2B for pin 3.

I want to get PWM output pin value.

The pin will either be 0 or 1.

analogWrite(pin, 100);

It will be 1 for 100/256 (39%) of the time, and 0 the rest of the time.

Why do you want to do this?

Because I'm seeking a solution for solving this question without creating a new variable for store the PWM value.

As mentioned in another answer you could interrogate the timer's register to see what value the analogWrite put there, but why bother doing this obscure thing (which would change for every output pin) when you can save the value in one byte in a variable? Also, that is not the "output pin value" but the duty cycle of the PWM output.


text:
Servo or motor with manual control
I am searching for a servo or motor with the ability to
easy manually controlling (turning) when power off.
What is the mechanism recommend to use?
Thank you for your answer.

please explain how your question is about the Arduino ....... arduino-uno and arduino-nano tags do not count

Motor that has no gearbox will be easier to manually turn when it is not powered.
Now, I don't know what you categorize as "easy" but this info will give you a starting point.
And I don't get why the use of the "arduino-nano" and "arduino-uno" tag