text:
addt instruction of Nextion Display
I'm new to Nextion display. I'm doing a model of oscilloscope with the display and an Arduino Uno. I used the waveform component. I went through the instruction set and found two instructions to send data to the waveform component. The instruction "add" is clear to me. Tried and got the output. But the instruction "addt" is not clear to me. I sent the instruction
addt 1,0,30\xFF\xFF\xFF

I got something on the display which I'm not able to understand. Please someone explain what the instruction "addt" does....... I also came across the term "data pass through mode" under this instruction in the documentation. Please explain that too.....
Thanks in Advance.....

Do you know the "nextion instruction set" page? https://www.itead.cc/wiki/Nextion_Instruction_Set#addt:_Add_data_to_waveform_component_in_volume

Yes....I have gone through it. I learner about add instruction from that only. But I'm not able to understand what addt instruction does.....

The third parameter for the "add" command is "val", the value. The third parameter for the "addt" command is "qty", the number of bytes that will follow. In your example you have '30', so you need 30 bytes with data between '30' and '\xFF\xFF\xFF'.

So, do I have to give 30  values with commas between "30" and "\xFF\xFF\xFF"????

I'm not sure anymore how this special mode works. I'm looking for an example but did not find it yet. I think the addt command has to be closed by the '\xFF\xFF\xFF' and after that the data follows.

I have it working. Some confusion in the documentation I think. First, a plot maximum value is the height of the plot.  For example, if the plot height is 190, then data will clip at 190.
void GuiAddEscWrite(char* str)
{
    int len = strlen(str);
    for (int i = 0; i < NUM_ENDING_ESC; i++) str[len + i] = 0xff;
    NEX_COM.write(str, len + NUM_ENDING_ESC);
    str[len + NUM_ENDING_ESC] = 0; // end string
}

//addt <waveform>, <channel>, <qty>
void GuiShowWaveform(char* data, uint32_t channel, uint32_t qty)
{
    char str[255];
    sprintf(str, "addt %d,%d,%d", idPlotRGB, (int)channel, (int)qty);
    GuiAddEscWrite(str); // add ffffff
    for (uint32_t i = 0; i < strlen(str); i++) Serial.printf("%c", str[i]); Serial.println();
    delay(5);
    for (uint32_t i = 0; i < qty; i++) Serial.printf(" %d", data[i]); Serial.println();
    NEX_COM.write(data, qty);
}

addt is the volume variant of add.
Instead of using something like:
add 1, 0, 19
add 1, 0, 39
add 1, 0, 85
add 1, 0, 98

you can group them all together with an addt:
addt 1, 0, 4
<5ms delay>
\x13\x27\x55\x62

The third parameter of the addt command is the number of values you want to send. Then you have to leave at least 5ms after sending the command so the display is ready to receive (it will actually send a "go" signal to you of \xFE\xFF\xFF\xFF.  You send the data as raw binary values (shown as C string escape sequences above), and after it has received the specified number it responds with an "ok" signal of \xFD\xFF\xFF\xFF.
The maximum number of values you can send in one batch is 128.

I tried a sample code...
SoftwareSerial nextion(10,11);
nextion.print("addt 1,0,5");
delay(5);
nextion.print("\x12\x13\x14\x15\x16\xFF\xFF\xFF");
didn't get anything on the screen. Is what I wrote wrong???

@Majenko, could you add the \xFF\xFF\xFF after the 'addt' command, and add reading the 'go' signal from the serial input in your pseudo code?


text:
Installing CH34xVCPDriver on mac
I've tried to install CH34xVCPDriver on my Mac M3 Sonoma and it's not working no matter what I do. I get an error message that says:
Install Tips error: The operation couldn't be completed.
(OSSystemExtensionErrorDomain error 10.)

what's not working? ... the installation process? ... the driver after installation?

The error you encountered (OSSystemExtensionErrorDomain error 10) typically means there is an issue with macOS blocking the installation of third-party system extensions. This can happen when the driver is not properly signed, or macOS's security features like SIP (System Integrity Protection) are preventing the installation.
If you haven't tried and you are sure that the OS version supports the driver, go to System Preferences > Security & Privacy and in the General tab, look for a message stating that the system software from the developer was blocked. Click on Allow and try the installation again.

source: Stack Exchange

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

sort: votes


text:
How to increase sensitivity of Capacitive Touch Switch?
I am working with Capacitive Touch Sense technology.In that I am using TTP224 Touch detector IC. I am getting good sensitivity when I am using Touch pad without putting any non electric material over it and able to switch ON/OFF connected led.But when I put any non electric material like Acrylic Sheet of 2mm thickness I am not able to get any signal through pad or not able to ON/OFF connected led.
So, How can I increase sensitivity of Touch pad?
I have bought TTP224 module from here.
And what can be the alternatives for TTP224???

Try a different material. Also try to minimize any gap between the pad and the acrylic. Otherwise exchange the capacitors on the board.

@Gerben...Thanks. There is no gap between pad and acrylic. And yes I am trying with different capacitor values.

According to the datasheet (if you can name it that):

The capacitance Cs0~Cs3 can be used to adjust the sensitivity. The value of Cs0~Cs3 use smaller, then the sensitivity will be better. The sensitivity adjustment must according to the practical application on PCB. The range of Cs0~Cs3 value are 0~50pF.

So, reduce the capacitances Cs0 to Cs3 and you will get better sensitivity.

Sometimes things just ****. In my case, where 0.5 mm more of gap make the TTP223 unable to work, because I designed such a small pad. My solution? Remove the paint in the PCB, put a lot of solder in to make the pad taller. Work like a charm.

remove all c3 to c10 capacitors of 22pf. This will increase sensitivity and will sense through 5 mm sheet also .

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

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


text:
MAX31855 giving NaN after some readings
In my current project I am measuring temperature using K-type thermocouple and MAX31855 breakout board and Arduino uno.
I have used Adafruit-max31855 library and example code from that library. But monitoring on serial monitor after some reading it is giving NaN.
Here is the code I have used:
#include "Adafruit_MAX31855.h"

int thermoDO = 5;
int thermoCS = 6;
int thermoCLK = 7;

Adafruit_MAX31855 thermocouple(thermoCLK, thermoCS, thermoDO);

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

  Serial.println("MAX31855 test");
  // wait for MAX chip to stabilize
  delay(500);
}

void loop() {
  // basic readout test, just print the current temp
   Serial.print("Internal Temp = ");
   Serial.println(thermocouple.readInternal());

   double c = thermocouple.readCelsius();
   if (isnan(c)) {
     Serial.println("Something wrong with thermocouple!");
   } else {
     Serial.print("C = ");
     Serial.println(c);
   }
   //Serial.print("F = ");
   //Serial.println(thermocouple.readFarenheit());

   delay(1000);
}

Circuit Diagram:

Output:

What could be the possible error for this and how can I solve this?

Add the actual problematic output from the Serial Monitor. We need to know whether you're gettin NaN from the internal temperature reading or the thermocouple reading.

Maybe this could help: https://forums.adafruit.com/viewtopic.php?f=19&t=119545

Does the error appear after a set time? Does it come good if you wiggle the wires? What about if you wiggle the thermocouple soldered to the board? Do you have another Adafruit board to compare it with?

Did Edgar Bonet's answer give you any answers. Did it solve your problem?

Try to Serial.println(thermocouple.readError()). It will give you an
error code, which is a bit field:

1 = open circuit
2 = short to ground
4 = short to Vcc

C.f. the
datasheet.

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


text:
PCF8583 with Arduino delay of one second?
I'm trying to interface the RTC chip : PCF8583 with Arduino Uno. I'm using exactly the circuit shown below except instead of the variable capacitor near the crystal oscillator, I've used a 22pF ceramic capacitor.

For the programming side, I've used the Arduino PCF8583 library
The code I'm using is the following :
#include <Wire.h> // necessary, or the application won't build properly
#include <stdio.h>
#include <PCF8583.h>

/*
*  read/write serial interface to PCF8583 RTC via I2C interface
*
*  Arduino analog input 5 - I2C SCL (PCF8583 pin 6)
*  Arduino analog input 4 - I2C SDA (PCF8583 pin 5)
*
*  You can set the type by sending it YYMMddhhmmss;
*  the semicolon on the end tells it you're done...
*
*/

int correct_address = 0;
PCF8583 p (0xA0);
void setup(void){
 Serial.begin(9600);
 Serial.print("booting...");
 Serial.println(" done");
}

void loop(void){
 if(Serial.available() > 0){
   p.year= (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48)) + 2000;
   p.month = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   p.day = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   p.hour  = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   p.minute = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   p.second = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48));
   // Use of (byte) type casting and ascii math to achieve result.

   if(Serial.read() == ';'){
     Serial.println("setting date");
     p.set_time();
   }
 }

 p.get_time();
 char time[50];
 sprintf(time, "%02d/%02d/%02d %02d:%02d:%02d",
  p.year, p.month, p.day, p.hour, p.minute, p.second);
 Serial.println(time);
 delay(3000);
}

When setting the time and date, everything went ok, but when getting date/time the result is always HALF the period of the elapsed time, for example if I set the time 10:30 and I check it after 30 MINUTES, I get 10:45 instead of 11:00.
I really don't know if this is a hardware or software issue. If anybody has any idea about this issue, that would be highly appreciable !
Thanks in advance !

I'm sorry, but that serial reading code is awful. Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

It seems to me the 3 V battery serves no useful purpose.

Shouldn't VCC (PCF8583 pin 8) be connected? Together with the diodes and battery backup?

Check your schematic vs the datasheet and make sure that it makes sense.
Check to make sure that your input is right. You can print it back right away, or set the etc to a known good time and see if it keeps time.
Check the library to make sure that it is good.


text:
Door control with Arduino and limit switches
I want to make a door with two limit switches and three buttons: one for stop and the other two for open and close. I run into a problem with the code with the start buttons and the limit switches. I can't make the code because I'm a beginner. Please can somebody help me with some code or something like that?
I'll appreciate it if you help me, because it's for my school project:)

Try something simpler first yourself: one button, try to read it; than a switch and try to read it; from there you make requirements for what you need. And if you run into a more specific problem you can ask again here; you also need a motor to open/close the door I assume?

Please provide a code that you have done, which is not working.

How does "help me with some code..." help you learn anything? There are many tutorials and example sketches to try out and build an understanding about how the Arduino can be used. There are no free lunches in the real-world :)

You will need to write code to

Control a motor. Likely a DC motor with two way control. This can be done with four MOSFETs and several diodes or much better, one H bridge IC. Your code will need to determine which one of two lines going to the dc motor is getting connected to the positive rail, and which one to the negative/ground, or both disconnected, using the three buttons you described.
You will need to write code that monitors the limit switches. I would suggest you use interrupts for these. One pin goes to ground, the other goes to the Arduino interrupt pin. You can use attachInterrupt() function to write functions that execute right away. Make sure you read up on which pins on your Arduino will support interrupts.
You will need to stop the motor movement either directly or by throwing a switch using the interrupt (or whatever detection method you use for the limit switch).

*one special consideration is that any variables that you use inside of interrupt functions should be marked as volatile, so int myVar; becomes volatile int myVar;
*also don't use Serial.print or millis() inside of your interrupt functions if can avoid it.

From here Google 'Arduino switch' and work on an implementation of limit switches separately. If you want to, Google 'Arduino Interrupts' and improve your implementation to use interrupts. Next, Google 'DC motor bidirectional control Arduino'. Work on it standalone. Once both work separately, combine into a single project.
Let me know as you go through these if you have specific questions, and I would be happy to help you learn how to build it using the components you have.


text:
Reading a monochromatic bitmap with Arduino for plotting
Complete newbie here.
I am following this thread:
How to read bitmap image on Arduino
Specifically the third reply from : frarugi87 in my attempt to plot a monochromatic bitmap image with a plotter device.
Basically: bitmap>SD card board>arduino uno> plotted image
I attempted to modify their code to work with monochromatic bitmaps and removed the print to file function:
    // MODIFIED CODE FROM BELOW CONTRIBUTOR

    // (c) Michael Schoeffler 2016, http://www.mschoeffler.de

    #include <SD.h> //Load SD library
    int chipSelect = 4; //chip select pin for the MicroSD Card Adapter
    File file; // file object that is used to read and write data

int32_t readNbytesInt(File *p_file, int position, byte nBytes)  // FUNCTION WHICH READS A DETERMINED AMMOUNT OF BYTES INTO A SINGLE VARIABLE
{
    if (nBytes > 4)
        return 0;

    p_file->seek(position);

    int32_t weight = 1;
    int32_t result = 0;
    for (; nBytes; nBytes--)
    {
        result += weight * p_file->read();
        weight <<= 8;
    }
    return result;
}

    void setup() {
      Serial.begin(9600); // start serial connection to print out debug messages and data

      pinMode(chipSelect, OUTPUT); // chip select pin must be set to OUTPUT mode
      if (!SD.begin(chipSelect)) { // Initialize SD card
        Serial.println("Could not initialize SD card."); // if return value is false, something went wrong.
      }

      if (SD.exists("bitmap.bmp")) { // if "bitmap.bmp" exists, say so
        Serial.println("Found The Bitmap File.");

      }

      file = SD.open("bitmap.bmp", FILE_READ);   // open the file to an object for reading

      // DETERMINE HOW LARGE THE BITMAP FILE IS
      int howmany;
      howmany = file.available();
      Serial.println(howmany);    // print the how large the file is

      // DETERMINE STARTING IMAGE ARRAY LOCATION IN THE BITMAP FILE
      int32_t dataStartingOffset = readNbytesInt(&file, 0x0A, 4);
      Serial.println("The starting location in the fiile is...");
      Serial.println(dataStartingOffset);

      // DETERMINE THE IMAGE HEIGHT AND WIDTH
      int32_t imgwidth = readNbytesInt(&file, 0x12, 4);
      Serial.println("The image width is the following pixels:");
      Serial.println(imgwidth);
      int32_t imgheight = readNbytesInt(&file, 0x16, 4);
      Serial.println(imgheight);

      // MODIFIED CODE. DOES THE COLOR DEPTH LOCATION WORK IN THE BITMAP AND DOES IT GIVE CORRECT INFO ABOUT THE FILE?
      int16_t pixelsize = readNbytesInt(&file, 0X1C, 2);
      if (pixelsize != 24)
      {
        Serial.println("This image is most definitely not 24 bpp");
        Serial.println(" it is actually a depth of :");
        Serial.println(pixelsize);

      }

       file.seek(dataStartingOffset);   //skip bitmap header and go directly to the image data array.

     /*  for(int32_t i = 0; i < imgheight; i ++) {
        for (int32_t j = 0; j < imgwidth; j ++) {
            B = file.read();
            Serial.println("height and width location from bottom");
            Serial.println(i);
            Serial.println(j);
            Serial.println("B");
            Serial.println(B);
        }
        Serial.println("height advance");
    }

*/
      int B;

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

            B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

        B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

            B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

            B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

        B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

    file.close();

    Serial.println("done write");

    }

But when I read a 16x16 monochromatic bitmap: see below

At what I assume is the color table starting location (given by dataStartingOffset variable).
I get strings two bytes of correct color information, followed by two bytes of just...zeros.
Is this a bitmap formatting thing?
Serial output for 16x16 bitmap looks like this:(only up to 9 of the 16 lines starting from the bottom)

Found The Bitmap File. 126 The starting location in the file is... 62
  The image width is the following pixels: 16 16 This image is most
  definitely not 24 bpp  it is actually a depth of : 1 1111111 11111110
  0 0 11111111 11111111 0 0 11111111 11111111 0 0 11111111 11111111 0 0
  11111111 11111111 0 0 11111111 11111111 0 0 11111111 11111111 0 0
  11111111 11111111 0 0 1111111 11111110 0 0 done write

And when I try to read a bitmap that is around 200 x 200 pixels, I get very strange height and width numbers that are negative and my above code does not work at all!
Does a 16x16 bitmap have different byte structure formatting than a 200x200?
Any help is appreciated. Again, I am a complete newbie here. I am just trying to figure out how to read a bitmap.

did the code work before you started to modify it?

check  your bitmap  file format here .... https://hexed.it/

That I do not know. It does give me correct values for a 16x16 monochromatic bitmap image (well...including the unwanted zeros), and the code seems straightforward, but I never tested it with a COLOR bitmap. I assume the person tested their code before posting.

never assume anything, but the code in that answer is very nicely formatted, so i would tend to trust it also ....... like i implied in my first comment, run the code unmodified

BMP file format table ..... http://www.ue.eti.pg.gda.pl/fpgalab/zadania.spartan3/zad_vga_struktura_pliku_bmp_en.html

I do agree on that. Test to see if the code works first. I'll try it with a color bitmap tomorrow and see what turns up.

Bitmap files (.BMP) have to have a row size that is a multiple of 4 bytes. Any extra space in a row has to be padded with 0.
Since your rows are 16 pixels wide that equates to 2 bytes. That's not a multiple of 4, so it is padded with to bytes of 0 to make it a multiple of 4.
Your code needs to take that into account and know that if it hasn't read a multiple of 4 bytes then to read enough "dummy" bytes to get to the start of the next row.
Also, note that BMP files are the only files in the known universe where the image data is stored upside down (starting lower-left corner instead of upper-left corner).

ah. That makes sense. Thanks for clarification. Any idea why I would be having confusion with larger bitmaps , like 200x200? The color table "start position" ends up being a very large negative number using the code that I posted.

Bitmaps come in numerous different data formats. You should inspect the header to find out what type it is. Here is a library for my chipKIT DisplayCore system (doesn't work with Arduino, only chipKIT), but feel free to take what you like from it.

A side note, Postscript and PDF also has the (0,0) origin at the lower left corner of the defined page area. One could possibly argue they are not image formats, but they do describe "ink" on a "page"


text:
Do I have to use Arduino IRRemote libraries?
I have seen some tutorials to build your own IR Remote. But all of them use a library that contains the IR code. The question is, could I just skip, injecting a library and make the Arduino output a IR signal?

Sure. If you really want to spend the time needed to both understand the IR protocol and write the code to generate the right signals.

it is fairly simple if you only want to emulate one remote control and only a few buttons ...... have you researched the TV remote control IR protocol? .... do you have any experience with an Arduino?

I dont even have a single Arduino. I thought it would be easier, but the libraries include the ir codes? Because I need ALL Power off ir codes.

google tv-b-gone   .... https://github.com/shirriff/Arduino-TV-B-Gone


text:
How to power an Arduino Nano without mini-B USB port?
I'm new to Arduino. I want to power my Arduino Nano with an external DC source, not with already attached mini USB port. I tried, but fail. Please help me to understand it. Thank you.

So what exactly did you try? What power source at what voltage did you connect at which pins?

I want to give 5V and I tried with pins 5v + GND and also with Vin + GND but no success

Should have worked if voltage, polarity and max current draw was correct. Read https://www.open-electronics.org/the-power-of-arduino-this-unknown/ Vin is the input to the 6-12V -> 5V voltage regulator. 5V is just the direct 5V net. Does the Arduino Nano still work when powered via USB or is it destroyed?

and I also tried with 12V on Vin + GND pins but no sign of power on nano

@MaximilianGerhardt Yes, Board is working with USB. LED is lighten up and I have uploaded code also in it

Do you have a multimeter to measure that a voltage is actually applied between the pins? Both methods for powering (Vin + 5V) should work (with the USB unplugged)

Sorry, I don't have multimeter :(

Just a thought in my mind, can it be damaged with static charge? I mean, some of the pins? : \

If it still works now when plugging it in via USB, it's still alive. If your USB port throws the device out, it's dead.

Duplicate of https://electronics.stackexchange.com/questions/60199/powering-arduino-nano-12volts

Thank you @MaximilianGerhardt and MatsK for being so sure and I figured out that it was my mistake to soldering wires loosly (Vin + GND) Sorry and thank you. :P


text:
Arduino button and led
Program below is my program for my button and LED, but it's not functioning the way I want it too. The LED is supposed to light up before I press switch 9, but it is lighting up immediately.
const int sw9=9;
const int sw10=10;
const int sw11=11;
const int sw12=12;
const int sw13=13;
int timer=250;
int s=0;
void setup()
{
  for (int opin=1;opin<=8;opin++)
{
  pinMode(opin,OUTPUT);
  pinMode(sw9,INPUT_PULLUP);
  pinMode(sw10,INPUT);
  pinMode(sw11,INPUT);
  pinMode(sw12,INPUT);
  pinMode(sw13,INPUT);
}
}
void loop(){
{
while (s==0)

for (int opin=1;opin<=8;opin++)
{
digitalWrite(opin,HIGH);
delay(timer);
digitalWrite(opin,LOW);
if(digitalRead(sw9)==LOW);
}

{
s=1;
delay(timer);
}
}
while(s==1)
for (int opin=1;opin<=8;opin++)
{
digitalWrite(opin,LOW);
if(digitalRead(sw9)==HIGH);
}
}

"LED is supposed to light up before i press switch 9 but it is lighting up immediately. " so before. I recommend to take a coding course

The only way you can more or less implement that requirement, is to use an ultrasonic distance sensor (e.g. HC-SR04), and measure the distance from the button to something coming towards it ... which hopefully presses the button and does not move away before pressed.

You will wind up in trouble later on if you don't do some kind of formatting. It becomes very difficult to read or edit code if everything starts from far left with no tabs or spaces. You can select everything and hit Control+T to autoformat your code. I agree with @Juraj, benefit yourself and take a basic coding class. YouTube is your friend.

if(digitalRead(sw9)==LOW);

if(digitalRead(sw9)==HIGH);

Both of these have the effect of "read the switch and then do nothing"
Change them to
if(digitalRead(sw9)==HIGH){
// do intended action
}


text:
RGB not working properly
My RGB led is not working properly. It should light up red when the ultrasonic sensor detects more than 10 cm and green when it detects less than or equal 10 cm. It is just blinking red and green at the same time. How do I fix this?
#include<Servo.h>
Servo servo1;
int Motor = 3;
int tpin = 7;
int epin = 6;
int red1 = 12;
int green1 = 13;
int pos = 0;
long duration, inches, cm;

void setup() {
    Serial.begin(9600);
    pinMode(tpin, OUTPUT);
    pinMode(epin, INPUT);
    pinMode(red1, OUTPUT);
    pinMode(green1, OUTPUT);
    servo1.attach(Motor);

}

void loop() {
    digitalWrite(tpin, LOW);
    delayMicroseconds(5);
    digitalWrite(tpin, HIGH);
    delayMicroseconds(10);
    digitalWrite(tpin, LOW);
    duration = pulseIn(epin, HIGH);
    cm = (duration / 2) / 29.1;
    inches = (duration / 2) / 74;
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
    delay(100);

    if ((cm > 10))
    {
        servo1.write(pos = 0);
        digitalWrite(red1, HIGH);
        delay(100);
        digitalWrite(red1, LOW);
        delay(100);
        Serial.println("\t RED");
    }
    else if ((cm <= 10))
    {
        servo1.write(pos = 90);
        digitalWrite(green1, HIGH);
        delay(100);
        digitalWrite(green1, LOW);
        delay(100);
        Serial.println("\t GREEN");
    }
}

What output are you seeing in the console?

RGB LED has nothing to do with the issue, so the title is misleading.

blinking red and green at the same time .... that means blinking yellow ..... is that correct?

The ultrasonic sensor scans every 0,1 seconds according to your code. Problem is, sometimes you have "faulty" results. Taking into consideration the frequency of your scans + the "faulty" scans, it could be that your arduino just keeps switching between those two LEDs.
What helped me back then was to make a counter. A variable, that counts how many times in a row the distance to the object is "distance <10cm". If the streak was interrupted, it would reset the variable. This is how a serial output would display it:
distance: 20cm
distance: 16cm
distance: 8cm
count: 1
distance: 9cm
count: 2
distance: 6cm
count: 3
distance: 8cm
count: 4
distance: 11cm
count: 0
distance: 12cm
distance: 20cm

And the moment your counter reaches a certain spot, for example the object is closer than 10cm five times in a row, then you will let an led light up
if(count>=5)
{
  //turn on green led (color may be wrong)
}
else
{
  //turn on red led (color may be wrong)
}


text:
Error: exit status 1 stray '#' in program
I got this error:
exit status 1 stray '#' in program

How can I remove this error..?
int keys = {1,2,3,A,4,5,6,B,7,8,9,C,*,0,#,D};

you should use char literals instead of numbers, operators, identifiers and macros.
just place every single list entry in single quotes like this {'1', ...'#', 'D'}

only some of the elements in keys are integers ... you need to rethink what you are doing

If s/he quotes every one that will be OK. A single quoted character can be stored in an int.

"How can I remove this error?" Well, just delete your code from the beginning to the end and this will certainly "remove the error". Done. Now, please, make an effort to ask questions that at least makes some basic sense. Yours currently doesn't make any. Until you tell us what you were trying to do and what is that # doing there, there's no way to answer your question.

There are several -more or less severe- issues in your one line of code
const char keys[] = {'1','2','3','A'
                    ,'4','5','6','B'
                    ,'7','8','9','C'
                    ,'*','0','#','D' };

( Find the differences :) )
Depending on your usage, you eventually even need a 2-dimensional array
const char keys[4][4] =  ...


text:
Why is there no hex file generated when I "build binary output" from the Arduino IDE?
I want to obtain the .hex file from my Arduino sketch. I have followed various guides but there is no .hex file in my output folder.
How can I obtain my hex file?
Here are my preferences:

This is the contents of my output folder

Based on your setting with the URL for esp8266 package and bin file name with "...generic" I assume you want it for esp8266.
esp8266 doesn't use hex format and "Export compiled binary" creates bin. You can upload it with esptool.
For AVR boards "Export compiled binary" generates hex. You can upload it with avrdude.

Ah, good catch :-)

Current versions of Arduino IDE
Use the menu option in the Arduino IDE:
Sketch ► Export Compiled Binary
See post #6 from the thread How to get hex file from arduino files ?:

Well, since it was bumped it's worth mentioning there is a new way to
  do this added in Arduino IDE 1.6.5:

Sketch > Export Compiled Binary
If you are doing this with an example then you will be prompted to save the sketch in another location.
Wait until the sketch has finished compiling.
Sketch > Show Sketch Folder
The .hex file will be in the sketch folder

Here is a screenshot for OS X:

There is no need to fully compile, a simple verify will suffice. From post #10:

Reopen Arduino, and open a sketch of your choice (use the Examples->Digital->Blink if you have no other sketches). Hit the Verify button to compile the sketch. Now, navigate to the build.path folder. You should see a bunch of files including one with a .hex extension.

Older versions of Arduino IDE
If using an older version of the Arduino IDE, from post #12:

Try this if using an older version of Arduino
Taking out HEX file from Arduino in 3 simple steps

Open Arduino IDE
File ► Preferences menu

Find "Show verbose output during " and check the "compilation" box
Locate the preferences.txt file and open it
Add the following line (this is the path to the directory where the hexfile will be stored):
build.path=C:\Users\<username>\Desktop\hexfile

Change the following line
export.delete_target_folder=true

to
export.delete_target_folder=false

Quit the Arduino IDE and restart it.
Now when you compile, the directory specified in build.path will contain the .hex file (along with other files which can be ignored)

did you read my answer?

Yeah, I had upvoted it... but I missed the ESP bit! I need to pay more attention :-)

Hi Greenonline, thanks for your thorough answer. Indeed it was the detail about ESP8266 spotted by Juraj that was the key to my issue, but i really appreciate your effort :)


text:
Keyboard.h not found
I keep getting this error message:
"'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?"

... when I have already included Keyboard.h.
#include <Keyboard.h>

void setup() {
  pinMode(3,INPUT_PULLUP);
  pinMode(4,INPUT_PULLUP);

 Serial.begin(9600);    //begin seral comms for debugging
}

void loop() {
  Keyboard.begin();
  if (digitalRead(3) == 0) //if button 3 is pushed
   {
Keyboard.write('z');
delay(200);
}
   else if (digitalRead(4) == 0) //if button 3 is pushed
{
  Keyboard.write('x');
  delay(200);
}
  Keyboard.end();
}

Keyboard.h is already included as a default library in Arduino so I'm not sure what's wrong

Which Arduino do you have? Please tag your question with that information.

Please update your question, stating which processor and/or board you are using.

If you have Arduino/Genuino Uno selected as your board in the Tools ► Board ► menu, then you get the error. If you select Arduino Leonardo it compiles correctly.
From Can't seem to be able use Keyboard.h library, this post states:

Keyboard.h (and Mouse.h) only works on devices that use the ATmega32u4 processor, like the Leonardo or Micro.  See: https://www.arduino.cc/en/Reference/MouseKeyboard

This solution might help though

I had the same problem using Flora
This worked for me:

Tools > Boards > Boards Manager
Install TeeOnArdu (Then select that board from Boards Manager)
Tools > USB Type > Serial, Keyboard, Mouse < Joypad
Upload and run code again (might need to restart IDE)

Great... btw, what Arduino board do you have?

was using a pro micro, it is detected as an arduino leonardo same chip i guess


text:
Won't break out of for loop
I'm new to Arduino and I'm trying to use PWM to generate a tone through a buzzer. I've created a for loop, however, the for loop doesn't seem to break when the variable ms is < 1000000.
int second = 1000000; //1 second in microseconds

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

void loop() {
  //Play middle C for 1 second
  for(int ms=0; ms <= second; ms+=3830)
  {
    digitalWrite(3, HIGH);
    delayMicroseconds(1915);
    digitalWrite(3, LOW);
    delayMicroseconds(1915);
    Serial.println(ms);
  }
  Serial.write("Finished C");
}

We can see on the serial output that the value of ms exceeds 1000000 but the for loop is still going. Can anyone see where I am going wrong?

An int can't hold 1000000.  It is a signed 16-bit variable, which means it can only hold between -32768 and +32767.
To store larger numbers you need to use long, or unsigned long which are signed and unsigned 32-bit variables.

Just one more question for my own understanding. Why on the serial output do values > 32767 display in the serial output?

ms may have been promoted to long since println expects long. However second will hold -31072. When you have the wrong variable type strange things can happen.

Ok thanks, at least I know now that it's important to think about what type a variable is.

In addition to Majenko's answer (an int on this platform can't hold a number greater than 32767) you have a second problem. You are evidently trying to make a middle C tone (261.6 Hz) by toggling a pin with a period of 1/261.6 seconds. However your Serial.println takes time. In particular at 9600 baud each byte you send will take 1/960 of a second (because there are 8 data bits, one start bit and one stop bit per byte), and assuming the number you are printing is roughly 4 digits, plus carriage return plus linefeed, you are sending 6 bytes for each time around the loop.
6 bytes of 1/960 (1042 µs) would be 6252 µs which completely dwarves your delays of 1915 µs.
Whenever you try to do things with timing loops you need to take account that everything in the loop takes time, not just your delayMicroseconds statements.


text:
Unexpected behavior of ++myCount
I'm new to Arduino and C.
This behavior is not what I'd expect:
Serial.begin(9600);
while ( ! Serial );

int myCount = 0;

for (int i=0; i<10; i++) {
    myCount = min( ++myCount, 8 );
    Serial.print( myCount );
    Serial.print( "  " );
}

I would expect:
1  2  3  4  5  6  7  8  8  8

But I get:
2  4  6  8  8  8  8  8  8  8

Why is my code counting by 2?

Because of the way the min() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results: https://www.arduino.cc/reference/en/language/functions/math/min/

if min is a macro such as #define min(a,b) ((a)<(b)?(a):(b)) think about what happens when you expand min( ++myCount, 8 ) .... you get ((++myCount)<(8)?(++myCount):(8)) - however, I didn't think it was a macro, so that's odd

Jaromanda X is indeed correct - min() is defined on line 92 of Arduino.h, thusly:
#define min(a,b) ((a)<(b)?(a):(b))

Therefore when the ++mycount is substituted for the a, it is in fact substituted twice, in both the (a)<(b) and the (a):(b), leading to the increment by 2, each time min(++mycount,8) is executed.
As VE7JRO mentions, as it is defined in this way, the reference for min(x,y) states:

Warning
Because of the way the min() function is implemented, avoid using
  other functions inside the brackets, it may lead to incorrect results
min(a++, 100);   // avoid this - yields incorrect results

min(a, 100);
a++;            // use this instead - keep other math outside the function

As the second example states, keep any incrementing outside of the min() macro.
Alternatively, I think that you could use the inline function to workaround this issue:
#undef min
inline int min(int a,int b) {return ((a)<(b)?(a):(b)); }

Because inline provides a real function call (with parameters) it avoids the use of macros and substitution, which gives rise to the issue that you encountered.
inline is a much better (safer) way to implement the functionality provided by macros, in many cases. For more information, see Inline functions in C++ or read a C++ reference.

The advantage of using a macro is it is type agnostic. You can use it with float, double, char, int, long, signed or unsigned, and it doesn't care.

esp8266 has min() as template function.


text:
MFRC522 not scanning card
So I have an Arduino Uno and an MFRC-522 reader, using a breadboard I've wired it up according to the example sketch which is the mfrc522 DumpInfo sketch.
/*Typical pin layout used:
 *
 *             MFRC522      Arduino
 *             Reader/PCD   Uno/101
 * Signal      Pin          Pin
 * -------------------------------
 * RST/Reset   RST          9
 * SPI SS      SDA(SS)      10
 * SPI MOSI    MOSI         11 / ICSP-4
 * SPI MISO    MISO         12 / ICSP-1
 * SPI SCK     SCK          13 / ICSP-3
 */

I've checked the wiring hundreds of times. The console shows
    Firmware Version: 0x92 = v2.0
    Scan PICC to see UID, SAK, type, and data blocks...
but getting a card near the chip, will not scan or dump any info no other information appears on the serial monitor.
I've tried with mifare classic 1k  cards
a Nexus 6
and a Samsung Galaxy S7
Edit: Everything
    /*
    * ------------------------------------------------------------------------------------------------------------------
    * Example sketch/program showing how to read data from a PICC to serial.
    * --------------------------------------------------------------------------------------------------------------------
    * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
    *
    * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
    * Reader on the Arduino SPI interface.
    *
    * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
    * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
    * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
    * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
    * when removing the PICC from reading distance too early.
    *
    * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
 * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
 * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
 * keep the PICCs at reading distance until complete.
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
    Serial.begin(9600);     // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init();     // Init MFRC522
    mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
    Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }

    // Dump debug info about the card; PICC_HaltA() is automatically called
    mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

datasheet Nxp website /documents/data_sheet/MFRC522.pdf

Phones mosly use NFC which is at a higher freaquency then RFID. Are you sure they are even compatible?

Pretty positive, But I also used many MiFare Classic cards which this reader is explicitly stated to be compatible with. with absolutely no results

Can you post the whole post please?

Edited main post

Have you read MFRC522.h? It seems the 1K tags have a specific type of authentication. Also, be sure that the device has adequate power, during transmit it may suddenly use a lot more power. You may ultimately try another reader or card, to exclude any possible hardware defects in the antenna circuitry.

I had a similar problem. I used I2C to check if the board can see the reader. If I2C Bus doesn't detect your reader, then one of your soldering must be faulty... check with a meter and carefully re-solder the erring pin.

The OP says "the console shows Firmware Version: 0x92 = v2.0". This effectively means that there is a working connection with the reader. So any advice on resoldering doesn't seem useful at all.

I have several of this board with this condition. As I checked ,they all return the same thing as you send in SPI . I think all of them have hardware problem. Common thing for all of them is In past I supplied them with switching supply and I think this is why they got broken(this chip is very sensitive with supply voltage and YOU MUST NOT CONNECT THEM TO MORE THAN 3.3V EVEN FOR VERY SHORT TIME) . I highly recommend use of Linear regulator for them

your breadboard can be buggy. In addition, are you connected VCC to 3V or 5V?
As I remember, you need to connect it to 3V.

#include <SPI.h>
#include <MFRC522.h>

void setup() {
  Serial.begin(9600);
  SPI.begin();
  RFID.PCD_Init();      // MFRC522
}
#define SS_PIN 10
#define RST_PIN 9

MFRC522 RFID(SS_PIN, RST_PIN);

void loop() {
  if (!RFID.PICC_IsNewCardPresent() || !RFID.PICC_ReadCardSerial())
    return;

  String buffer;
  for (byte byte = 0 ; byte < RFID.uid.size ; byte++)
    buffer += String(RFID.uid.uidByte[byte] < 0x10 ? " 0" : " ") + String(RFID.uid.uidByte[byte], HEX);
  Serial.println("NUID: " + buffer);

  RFID.PICC_HaltA();
  RFID.PCD_StopCrypto1();
}

I figured out that one get these kind of problems (reader get´s firmware version but can not read tags) are related to power consumption. I tried to power the reader with Heltec Lora 32 Dev board and it schowed exactly this behaviour. Now, connected to another 3,3V source everything works as it should :)

Same problem as above. Three card readers. Two worked. One didn't. All three  readers had two pins bridged on the reader chip. The bridged pins were close to the pin 1 corner. I left the bridge alone as all three readers had the same bridge and one of the pins did not have a trace to it. The faulty card reader also had two pins bridged with solder in a different location. Both pins had separate traces. I removed the solder bridge and the faulty card reader was no longer faulty.

Maybe you need a function TO PRINT THE READINGS!!!
This is the loop and a function to print it:
void loop() {
  if ( ! rfid.PICC_IsNewCardPresent())
    return;
  if ( ! rfid.PICC_ReadCardSerial())
    return;

    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }

    Serial.println(F("The NUID tag is:"));
    Serial.print(F("In hex: "));
    printHex(rfid.uid.uidByte, rfid.uid.size);

  rfid.PICC_HaltA();
  rfid.PCD_StopCrypto1();
}

void printHex(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }

}

mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
Already prints to serial. It's almost like I actually know what I'm doing as far as code goes.
in fact I already have my whole project written for this card. it just seems to not actually read anything.


text:
I am getting blocks on my lcd screen 16*2
When I have tried interfacing my 16*2 LCD with Arduino I am getting only the black coloured boxes on my screen. What might be the problem?
Is there any solution to that? Do I need to connect any additional physical device to avoid that situation?
product is here lcd display 16*2

Hello and welcome to arduino.stackexchange. Your problem is a common one and relates to the contrast settings. PIN3 of your LCD needs a potentiometer which will allow you to change the contrast.

it's very unusual for the lcd being faulty. since there is no pic that shows how you have connected the lcd i cannot say anything. however you can search "dronebot workshop lcd" on YouTube. Mr Bill had explained it very well he also shows how you can control the lcd by only four wires. go and see that video.

You should post a picture of the LCD, name the library you are using to interface it, and post your code that initializes it and attempts to send data to it.

There are two possible problems, and you haven't stated which it is.

A single row of blocks (just the top row)

This is caused by either bad communication (wrong wiring) or incorrect code. Basically, the display isn't being initialized properly by your code for whatever reason.

Two rows of blocks (the entire display full of blocks)

The display is being initialized properly, so both your code and wiring are correct.  However, the contrast setting of the display is wrong. You need to check the wiring for your contrast potentiometer and adjust as necessary.

+1 on the contrast comment.


text:
Changing the light state
Can someone give me a solution to the following problem?
I have 1 IR remote, blynk app,some pushButtons and also 1 relay module.
(I set 1 pin of ATMega as input to be able to read what esp sends when I use the blynk app).
So basically what I want to do is this:
If I press btn1 from the IR Remote or PushBtn nr1, or I send 1 from blynk app
then relay 1 must turn on. For now that part works.
Anyway, what I want to do next is this:
If the relay is turned on (closed) I want to be able to turn it off using the same buttons (for which I have set a counter and I call that variable).
Now I can turn the relay off only if I use the same btn that previously I have used to turn it on. But I want to be able to turn it off the other way.
If I used the blynk app to turn it on then if I press the pushbtn second time - I want it to be off. Also if I don't press the pushbtn but I use the IR remote and press 1 2 times- the relay should be off.
if(cntbtn2 == 1 || cntPushbtn2 == 1)
      {
      digitalWrite(rel2,LOW);
      u8g.setFont(u8g_font_courB10);
      u8g.drawStr(32,10,"Interior");
      u8g.drawFrame(0,12,128,51);
      u8g.drawLine(64,12,64,62);

      if(cntbtn1 == 1 || cntPushbtn1 == 1)
          {
          u8g.setFont(u8g_font_5x8);
          u8g.drawStr(10,23,"Sufragerie");
          u8g.drawStr(15,60,"L.aprinsa");
          u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
          }

      else if(cntbtn1 != 1)
          {
          u8g.setFont(u8g_font_5x8);
          u8g.drawStr(10,23,"Sufragerie");
          u8g.drawStr(15,60,"L.stinsa");
          u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
          }

      u8g.drawStr(73,23,"Dormitor");
      u8g.drawStr(75,60,"L.aprinsa");
      u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
      }

else if(cntbtn2 == 2)
    {
    if(cntbtn1 == 1 || cntPushbtn1 == 1)
        {
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(10,23,"Sufragerie");
        u8g.drawStr(15,60,"L.aprinsa");
        u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }
    else{
        digitalWrite(rel2,HIGH);
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(10,23,"Sufragerie");
        u8g.drawStr(15,60,"L.stinsa");
        u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }
    }

if(cntbtn2 == 1 && cntPushbtn2 == 2)
    {
    digitalWrite(rel2,HIGH);
    }

//ecran stanga
if(cntbtn1 == 1 || digitalRead(espPin) == 1 || cntPushbtn1 == 1)
    {
    digitalWrite(rel1,LOW);
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(32,10,"Interior");
    u8g.drawFrame(0,12,128,51);
    u8g.drawLine(64,12,64,62);
    u8g.setFont(u8g_font_5x8);
    u8g.drawStr(10,23,"Sufragerie");
    u8g.drawStr(15,60,"L.aprinsa");
    u8g.drawBitmapP( 20, 8, 16, 64, LightOn);
    if(cntbtn2 == 1 || cntPushbtn2 == 1)
        {
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.aprinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
        }
    else
        {
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }

   }

else if(cntbtn1 == 2)
    {
    digitalWrite(rel1,HIGH);
    u8g.setFont(u8g_font_courB10);
    u8g.drawStr(32,10,"Interior");
    u8g.drawFrame(0,12,128,51);
    u8g.drawLine(64,12,64,62);
    u8g.setFont(u8g_font_5x8);
    u8g.drawStr(10,23,"Sufragerie");
    u8g.drawStr(15,60,"L.stinsa");
    u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
    if(cntbtn2 == 1 || cntPushbtn2 == 1)
        {
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.aprinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOn);
        }
        if(cntbtn2 != 1)
            {
            u8g.drawStr(73,23,"Dormitor");
            u8g.drawStr(75,60,"L.stinsa");
            u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
            }
        }
    else
        {
        digitalWrite(rel1,HIGH);
        digitalWrite(rel2,HIGH);
        u8g.setFont(u8g_font_courB10);
        u8g.drawStr(32,10,"Interior");
        u8g.drawFrame(0,12,128,51);
        u8g.drawLine(64,12,64,62);
        u8g.setFont(u8g_font_5x8);
        u8g.drawStr(10,23,"Sufragerie");
        u8g.drawStr(15,60,"L.stinsa");
        u8g.drawBitmapP( 20, 8, 16, 64, LightOff);
        u8g.drawStr(73,23,"Dormitor");
        u8g.drawStr(75,60,"L.stinsa");
        u8g.drawBitmapP( 78, 7, 16, 64, LightOff);
        }
   }

your code is badly formatted ... the indentation is all over the place .... that makes it difficult to follow the program flow ... please fix the indentation

how should it be? is written in arduino ide. that editor identation is bad.

Re “that editor identation is bad”: the IDE is just a writing tool. It is not responsible for what you write. You are. It is willing to help though, if you ask nicely: “Tools → Auto Format”.

Split the logic and the buttons in separate parts and avoid code duplication.
First step is to determine what should control the relay state:
// pseudo code follows
if (pushButton.isPressed() || blinkApp.sentCommand() || conditionAlfa.isMet()) {
  // update condition is met, proceed to state change
  relayState = !relayState; // swap relay state
  updateRelay = true; // activate the part responsible for the change
}

Once the new desired state is set, act on the relay and update the screen accordingly:
// pseudo code again
if (updateRelay == true) {
  updateRelay = false; // we are now going to update, don’t do it again if not necessary
  relay.setState(relayState); // update the relay, no matter what was the event source
  screen.drawGraphics(); // update the screen, no matter what was the event source
}

If you split the two parts you start operating on logical conditions rather than on physical events, making your entire code cleaner and your task simpler.

i am new in programming and don't know so well many concepts. Also i have a question about the last part of the code you posted. if(updateRelay == true){updateRelay = false; } that will execute? i mean- the uC it looks at that condition and verify that is it true, but then when enter into the brackets, that condition not became false? and stop executing it?

updateRelay is just a "flag". It doesn't do anything by itself; it's a way to store the fact that the condition had been met. Once it has been tested (by if (updateRelay == true) { , its value is no longer needed; the following section will or won't be entered by if statement. So making it false again is just "housekeeping" for the next time around. You don't want to keep entering the if-clause after having seen the condition once; only when one of the conditions (button, blynk, etc.) becomes true again.

Thank you very much Robert.


text:
Arduino Genuino UNO
I have Arduino Genuino Uno and 'Extra PC' Debian Linux USB dongle. I can get board data S/N etc., but TX LED permanently lit and data showing on TX line with an oscilloscope. I get the following error message:
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied

An error occurred while uploading the sketch.
Any body know how to create this device?

what is Extra PC?

I think it means XTRA PC https://www.xtra-pc.com/ - which are these PC on a dongle thing, for windows XP, Vista, 7 .... not for connecting to a UNO

access rights https://www.arduino.cc/en/Guide/Linux#toc6

That is a overpriced and overrated usb flashdrive with linux installed on it. They ask 5 times more than the current prices for fast usb flashdrives. Grab an old usb flashdrive you already have, download the iso of your choice and use Rufus to put it on the flashdrive. Install it on a second fast flashdrive. Or try puppylinux which is loaded into ram for extra speed. All for free if you already have a flashdrive. Even a used ssd drive is cheaper than XtraPC. That will make a 10 year old computer run like a 3 year old computer. M Saunders, can you return it and get your money back?

Try it with sudo


text:
Read from serial monitor and put it in a array of byte
I'm a new here and this is my first question.
I would like to read from serial monitor and stock the information in a array of bytes. then I want to print this array in serial monitor.
This is the code that I tried:
byte A[6];

void setup()
{
}

void loop() {
  A[6] = Serial.read();
  Serial.write (A);
}

https://majenko.co.uk/blog/reading-serial-arduino https://majenko.co.uk/blog/arrays-pointers-what-c

If you want to print it only, I would suggest not to store it. But if you want to do some calculations, you might store it.
The problem you make is you always store the value in the 6th element of the array A, however A only has elements A[0] to A[5], so A[6] is beyond the storage space, and results in crashes (sometimes) or at least unexpected behavior.
To fix it you have to store the value in the correct element of A, and for that you need an index variable. Since you can only store 6 values, after the 6th, start with the 0 and process it.
Like:
byte arr[6];
index arrIndex;

void setup()
{
   arrIndex = 0;
}

void loop() {
  // Read serial.
  arr[arrIndex] = Serial.read();

  // Increase counter
  arrIndex++;

  // If the maximum is read, print values and reset it.
  if (arrIndex == 6) {
     // Print the elements.
     for (index = 0; index < 6; index++)
     {
        Serial.write(A[index]);
     }

     // Restart counter.
     arrIndex = 0;
  }
}

An improvement: instead of 6 everywhere, use a define:
#define MAX_ELEMENTS 6

Hey Michel,
Thank you for your response--
I tried your code but some question marque keep showing up .
if i print for example 11111. the Serial monitor show
?????????????????????????????????????????????????????????????????????????????????????????????????11111

I assume the read data are characters, if you try to print out non ascii values you might get the ? values... Try converting it to a string (with itoa(...) for example. Or maybe using an int array helps (not sure, cannot test it here).

I didn't explain it well, actually the question mark keep showing even if I print nothing. when I print something, the Serial monitor show it then go back to the next line

use https://www.arduino.cc/reference/en/language/functions/communication/serial/available/

You're welcome, good luck with your project


text:
Can I program an ATtiny87 with Arduino
I have a project, and I want to use an ATtiny167(ATtiny87), I know that an Arduino can progam ATtiny84 (84/44/24), ATtiny85 (85/45/25), and ATtiny2313 (4313). but I don't know if it can program an ATtiny87?
thank you for your help.

There is a json for ATtiny 167 at https://playground.arduino.cc/Main/ArduinoOnOtherAtmelChips
So add that json to your preferenses.

Having same issue. Installed https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json already. Trying to program the Roshamglo with virtual USB 1.1 via Micronucleus but even when the device is in and in Bootloader mode, I can not see it with lsusb or in micronucleus. Any suggestions?


text:
First Arduino Uno - Immediate Problems
I'm new to Arduinos but researched thoroughly before buying one. Just for context I'm an IT Professional with 20 years in the game, I'm comfortable with Linux/Unix, Windows, Raspberry Pi's, electronics, hardware, software and monitoring/switching COM ports.
I've purchased my first Arduino (actually a Elegoo Uno R3 clone) and have just tried it out of the box connected to two different systems; one Windows 7 64bit Enterprise the other Kubuntu. Despite having the correct COM port selected on both I'm getting similar error messages:
**avrdude: ser_open(): can't open device "\\.\COM15": The system cannot find the file specified.**

or
**avrdude: ser_open(): can't open device "\\.\COM6": Access is denied.**

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

Yes I have tried different COM ports.
Yes I have tried turning off Firewalls
Yes I have tried different USB cables.
I have a solid green LED and a intermittently blinking orange LED.
The suggested Troubleshooting guide + many Forum Threads do not seem to cover this exact error I'm encountering - well they do but they tend to be people with the simple issue of them not selecting the correct COM port or having the same COM port tied up with another task. Then choose the correct port and it works. I'm confident I have the correct COM port and when I click Get Board Info it pulls down the correct board information and serial number etc.
On the Linux system I was seeing a similar behavior with slightly different wording: Permission Denied
On my Windows 7 system I run as a Standard User (as one should, not as an Administrator), but regardless I have tried running the Arduino application normally and as an Administrator user but it has the same result. And it seems strange that it encounters the same style of error across multiple different operating systems.
Have I just been really unlucky and got a dud for my first Arduino or am I missing something obvious?
Thanks for your time and help.

refer to the windows device manager ...... does a comport device appear in the device tree when you plug the arduino into the USB port?

You didn't mention drivers in your troubleshooting - have you installed the USB-chip drivers on your PCs? The clone boards come with a different USB <-> TTL Serial chip or firmware (not sure which) than the Italian boards and require CH340 drivers on the PC side to talk to it. (Whereas many OSes include drivers for the FTDI firmware/protocol used on Italian boards). If not, you can find them on the Downloads section of Elegoo's site.

Yes it does, I think you may have missed certain elements of my initial post. I'm very confident with the selection, monitoring and configuration of COM ports.

Thanks @JRobert for that insight. I've tried downloading the CH340 drivers from Elegoo's website and installing those but no change.

@JRobert I think you may have just nailed the problem with your CH340 comment - I didn't think it had worked initially after installing, but after a reboot it began to work on my Win7 64 bit system! Thank you. At least this proves to me that the Uno board is not broken and is worth wrestling with on other operating systems if I have to. Thank you everyone for your time and help.

On Linux "Permission Denied" generally means one of two things:

You're not in the dialout group (or you haven't logged out and logged in since), or
Something else is using the serial port.

For 1:
sudo usermod -a -G dialout ashley
<log out or reboot>

For 2:
The most common culprit is ModemManager. The simplest cure is to uninstall it:
sudo apt-get remove modemmanager

I assume ashley would be your username.

@Gerben No, mine would be matt. Ashley's would be ashley... ;)

OP is on Windows. why an answer for Linux?

@Juraj He's on both Windows and Linux. Read the question: "and have just tried it out of the box connected to two different systems; one Windows 7 64bit Enterprise the other Kubuntu." and "On the Linux system I was seeing a similar behavior with slightly different wording: Permission Denied"


text:
My ESP8266 web server is only displaying text, even after ensuring content type is text/HTML
So I just got my two ESP8266/ESP-12E WiFi development boards in the mail as I am trying to set up a few home automation devices in my house. I've gotten much further than I thought I would today, considering this is my first foray into working with circuits that involve microprocessors/WiFi, but I've run into a problem that I can't find a solution to myself.  Forgive me if there is another question similar to this, but I could not find it and this seems like the best place to ask.
I am using a tutorial/template program that Rui Santos from Random Nerd Tutorials was kind enough to create ( https://randomnerdtutorials.com/esp8266-web-server/ ), and although we have (as far as I can tell) identical boards, operating systems and Arduino code, I keep getting an HTML page that is text only, with none of the CSS or HTML elements showing.  It should look like this:

However, I am getting a page that looks like this:

His serial monitor is giving this response:

My serial monitor is giving me this response:

I've tried putting client.println("Content-type:text/html"); in a few places to see if it would help display the page, but to no avail.  Any help with getting this little program/website running would be greatly appreciated.
Thanks for your time!

clearly you're adding the content-type incorrectly in the code you haven't shared, because if you added it correctly, it would be sent as a response header, as it is, your code that you haven't shared is putting content-type:...etc in the response body - but as the code you haven't shared is not visible, I could be wrong (but I'm not)

I've tried putting client.println("Content-type:text/html"); how about keeping it where the tutorial has it?

The program didn't display the page correctly as-is, that's why I tried that, I have zero experience with code until now so I figured I'd give it a shot.  What's the best way to show you the code?

Oh. So the original code is broken?

It's possible that there's a compatibility issue between the code and my esp8266 or my OS but nothing I can pinpoint.  There have been a lot of issues in the comments of that article but also lots of success stories, no issues reflect this problem though

Don't use the low-level tools to handle http, use the built-in http tools. They  make creating http responses trivial. No more concatenating headers or worrying about client status; it provides a nice clean function ex:server.send(404, "text/plain", message); and nice subscription method: server.on().
Checkout its usage on one of the Arduino ESP8266's built-in examples:
https://github.com/esp8266/ESPWebServer/blob/master/examples/HelloServer/HelloServer.ino

The use of HTTP here is fairly straight forward so I think printing out your own HTTP headers is OK, you just need to be very specific with the order and send exactly what the browser expects. Without seeing your code, my guess is that you're sending out a blank line to the client somewhere prior to the 'Content-type: text/html' line being sent or that you're not printing an empty blank line somewhere after the Content-type line is being sent. If your browser (the client) doesn't receive the HTTP protocol commands that it expects in the order that it expects, then it will default to displaying EVERYTHING you send it as either plain text or an HTML document. To illustrate exactly what is supposed to be sent to the browser in this example:
HTTP/1.1 200 OK
Content-type:text/html
Connection: close

<HTML>....

Note that there should be a empty line printed out after the Connection: close line and before you send any HTML. There should be nothing else sent to the client prior to the HTTP/1.1 200 OK line being sent and before your HTML code starts. If you don't follow the protocol, your browser will probably default to displaying everything plain text as you're seeing.
Something else I noticed in the example code, there is no space between Content-type: and text/html. This is unusual, but I guess it doesn't break the protocol and Firefox and Chrome handle it ok in my testing. Still, it could cause issues if a browser doesn't handle that properly so you might just try adding a space between the header and it's value.


text:
Turn off power to a moisture sensor except when reading values
I have an Arduino Uno and a moisture sensor (looks like a YL-69 clone) submerged in water. I need to read the sensor's (analog) value every 3 min or so. The problem is: the sensor is always powered by the Arduino (GND and VCC), i.e. the current passes through it at all times. Because of this, one of the sensor's electrodes (presumably containing copper) grows a cyan residue. I'd like to NOT supply any power to the sensor except for the brief moment when I need to read the value. How can I do this?
EDIT: I've just noticed a related question (link below). The user decided to intermittently power the sensor via a digital pin, rather than VCC. Is this reasonable?
Does a moisture sensor need warm-up time?

If your sensor draws less than 40mA to operate, then you can safely "power" it from an GPIO pin.
The related question also asks how long the sensor must be powered in order to get a stable reading. For a sensor such as this one, it appears to be a simple resistive voltage divider, with the moisture sensor itself providing one leg of the divider circuit. The active component appears to be a comparator to provide a digital HIGH/LOW output as an alternative to the analog output.
Most schematics show a capacitor between ground and the voltage divider output, presumably to reduce noise. You need to allow for this capacitor to charge up and become stable before you take a reading. The time for this depends somewhat on the value of that capacitor and the supply voltage you are using.
Safe to assume, however, that a wait time of 1 second is more than enough.

I built a project very similar to this last winter to monitor moisture levels in the soil of plants that I was keeping over winter in my basement.  I used GPIO pins to power the sensors similar to what jose can u c described above and  performed testing to determine the minimum on time to get readings.  I found that 150ms was enough to get stable readings in soils varying from completely saturated and with standing water to very dry (plant leaves starting to show signs of drying out).

Here are other anti-corrosion measures for moisture sensors I found:
A moisture sensor with gold-plated electrodes:
https://www.dfrobot.com/product-599.html#.UhflOL-N_H0
Replacing metal electrodes with graphite:
http://tuxgraphics.org/electronics/200908/eth-flower-watering.shtml
Capacitive (i.e. not resisitive) moisture sensor:
https://www.amazon.com/DFROBOT-Gravity-Capacitive-Corrosion-Resistant/dp/B01GHY0N4K/ref=cm_cr_arp_d_product_top?ie=UTF8
Non-corrosive high quality sensor ($$$):
https://www.vegetronix.com/Products/VH400/

I use in my project the fully waterproof sensor SMT50 (see http://www.truebner.de/en/smt50). It is specified from 3.3V to 30V power supply with a current of around 3 mA, so that should be possible to supply it from a GPIO. Please not that the GPIO output voltage decreases with current (see AVR datasheet pin driver strength).


text:
Writing to serial LCD seems to interfere with servos
I have an OBD-based Arduino project (OBD adapter link below) which uses two servos and a serial LCD from Sparkfun (link below). My problem: writing to the LCD seems to interfere with the servos. Details:
1) When all LCD-related code is excluded, the servos work smoothly.
2) When LCD-related code is included, but the servos are not hooked up, the LCD displays everything OK.
3) When the LCD-related code is included, even if the LCD itself is NOT hooked up, the problem occurs. There's a brief noise from the servos every time I write to the LCD (the servos don't move much, they just make a brief noise).
Any idea what's causing this? Below are the relevant parts of the code (OBD, servo, LCD):
#include <Arduino.h>
#include <Wire.h>
#include <OBD.h>
#include "MPU6050.h"
#include <SoftwareSerial.h>
#include <Servo.h>

int servoPin1=13;
int servoPin2=12;

Servo servo1;
Servo servo2;

COBDI2C obd;
SoftwareSerial lcd(2,3);

void clearDisplay() {
  lcd.write(0xFE);
  lcd.write(0x01);
}

void setLCDCursor(byte cursor_position) {
  lcd.write(0xFE);
  lcd.write(0x80);
  lcd.write(cursor_position);
}

void Show() {
  setLCDCursor(0);
  lcd.print("Test");
}

void setup() {
  lcd.begin(9600);
  clearDisplay();
  setLCDCursor(0);
  lcd.print("OBD");

  pinMode(servoPin1,OUTPUT);
  pinMode(servoPin2,OUTPUT);
  servo1.attach(servoPin1);
  servo2.attach(servoPin2);
  servo1.write(0);
  delay(200);
  servo2.write(100);
  delay(200);

  obd.begin();
  conn=obd.init(PROTO_AUTO);
  lcd.print("Connected");

  Wire.begin();
}

void loop() {
  conn=obd.readPID(PID_RPM,rpm);
  if (condition) {
     servo2.write(50);
    delay(500);
    servo1.write(100);
    delay(500);
  }
  Show();
  delay(1000);
}

OBD adapter
Serial LCD

You are using SoftwareSerial which turns interrupts off when sending/receiving in order to precisely time gaps between bits. The Servo library may use hardware timers, but to work on pins 12 and 13 would require interrupts to "copy" the pulses to those pins. Thus the copies will be distorted when writing to, or reading from, SoftwareSerial.
I suggest using hardware serial (pins 0 and 1) for talking to the LCDs, which does not turn interrupts off. Alternatively, implement the servo positioning using the hardware timers yourself, which (once set up) won't change the pulse widths if interrupts are turned off.

Thanks. I tried connecting the LCD data wire (pink in the schematic above) to either Tx or Rx (0 or 1) on the UNO. I removed all refs to SoftwareSerial and replaced all calls to "lcd." with "Serial." in the above code, but I'm getting garbage on the LCD. I tried different baud rates 4800,9600,19200 = all garbage. Is this the proper way to use the hardware serial?

To write to the LCD you need to use pin 1 on the board (Tx). Don't thrash around trying different baud rates, if 9600 worked with SoftwareSerial then it will work with Hardware Serial. You may need to unplug the LCD from pin 1 whilst uploading new sketches.

The servo control PWM signal is generated in HW.  So should be stable if left alone with adequate power despite what the code is doing.  Servos are analog devices.  So any perturbation in the shape or length of the wave form may affect the servo.
Consider, once the servo has reached the desired position, turning off the PWM signal which, for most servos, simply leaves them motionless where they are.


text:
Problem in integrating speed sensor LM393 with L298N
I am currently working on a project that has an automatic support wheel for bicycle.
The mechanism of this project is when the speed sensor is detecting the RPM of the rear bicycle wheel it will triggered the support wheel. The support wheel is oriented by the motor power. Basically, when the bicycle reaches a certain speed limit, it will activate the support wheel whether to move upwards or downwards. I have done some coding for this.
int sensor = 11;
unsigned long start_time = 0;
unsigned long end_time = 0;
int steps=0;
float steps_old=0;
float temp=0;
float rpm=0;
int motorPin = 9;

void setup()
{
{
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(motorPin, OUTPUT);
   Serial.begin(9600);

  pinMode(sensor,INPUT_PULLUP);
}
}

void loop()
{
 start_time=millis();
 end_time=start_time+1000;
 while(millis()<end_time)
 {
   if(digitalRead(sensor))
   {
    steps=steps+1;
    while(digitalRead(sensor));
   }

 }
    temp=steps-steps_old;
    steps_old=steps;
    rpm=(temp/5)/60;
    Serial.print("RPM = ");
      Serial.println(rpm,DEC);
      delay (1000);
      //Restart the interrupt processing

    if (rpm==0)
    {
      digitalWrite(8, HIGH);
      digitalWrite(7,LOW);
      analogWrite(motorPin, 255);
      delay(1000);

    }

   if (rpm>0.02)
   {
      digitalWrite(8, HIGH);
      digitalWrite(7,LOW);
      analogWrite(motorPin, 255);
      delay(1000);
      digitalWrite(8, LOW);
      digitalWrite(7,LOW);
      analogWrite(motorPin, 255);

   }

   }

The problem with this code is that I do not know how to stop the motor when the rpm>0 until the sensor read rpm=0. I want to make the motor rotate backwards for a few seconds and stop completely as long as the rpm is above zero (my coding will make the motor rotate forward when rpm>0 again and again, the same goes for when rpm=0) and it will only rotate forward for few seconds when the rpm=0 and stop completely until the sensor read rpm>0. The process continues looping.
Please help me, I'm new to Arduino and sorry for my English as I'm not really fluent in English.

the l298n can be made to go backwards by swapping the polarities of the direction pins. For e.g., if pin 8 and 7 are high and low respectively to go forwards, then make 8 low and 7 high to reverse direction. However it seems from your question you want to counteract the forwards movement as soon as it starts moving? How would this ever move the bike?


text:
Adafruit Feather 32u4 BLE compatible with Software SPI?
Let me preface by saying that I am not super experienced with electronics. I have an Adafruit Feather 32u4 that is using Hardware SPI to communicate over Bluetooth. Unfortunately, I'm also hoping to use the SD library, which also uses Hardware SPI. I am hoping to change the board to use Software SPI instead, so that the two may work together.
The Bluefruit code by default has the following commented out:
/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */
Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,
                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,
                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

Which leads me to believe I could use SW SPI but simply uncommenting this and commenting out the HW SPI doesn't seem to work.
I am just not sure if it's not compatible with the board, or I need to do more than this...?

SPI is a bus. you can wire more devices only use different  CS pin. some SD modules make problems on bus. the Adafruit SD module is OK

my comment applies to hardware SPI. two different sw SPI or sw SPI with hw SPI can't work together on the same pins

Read SparkFun's guide, Serial Peripheral Interface (SPI), especially the multiple slaves section:

Multiple slaves
There are two ways of connecting multiple slaves to an SPI bus:

In general, each slave will need a separate SS line. To talk to a particular slave, you'll make that slave's SS line low and keep the
rest of them high (you don't want two slaves activated at the same
time, or they may both try to talk on the same MISO line resulting in
garbled data). Lots of slaves will require lots of SS lines; if you're
running low on outputs, there are binary decoder chips that can
multiply your SS outputs.

On the other hand, some parts prefer to be daisy-chained together, with the MISO (output) of one going to the MOSI (input) of the next.
In this case, a single SS line goes to all the slaves. Once all the
data is sent, the SS line is raised, which causes all the chips to be
activated simultaneously. This is often used for daisy-chained shift
registers and addressable LED drivers.

Note that, for this layout, data overflows from one slave to the next,
so to send data to any one slave, you'll need to transmit enough data
to reach all of them. Also, keep in mind that the first piece of data
you transmit will end up in the last slave.
This type of layout is typically used in output-only situations, such
as driving LEDs where you don't need to receive any data back. In
these cases you can leave the master's MISO line disconnected.
However, if data does need to be returned to the master, you can do
this by closing the daisy-chain loop (blue wire in the above diagram).
Note that if you do this, the return data from slave 1 will need to
pass through all the slaves before getting back to the master, so be
sure to send enough receive commands to get the data you need.


text:
Help with coding Arduino Nano to run fan through slide switch at specific intervals
I’m trying to use Arduino Nano to run my 5 V PC fan, which, I know it sounds crazy, it’ll be mounted on a piece of Tupperware that’ll control the airflow through it via the fan. However I have no idea how to code the Arduino, but I do know how to code other things when I’ve done it in class. The setup is a 5 V rechargeable lithium ion portable battery connected to the switch which would be connected to the Arduino, and when the switch is triggered/flipped it would allow power to the Arduino, boot it up, and trigger the code that would tell the fan to run at specific intervals. The idea for intervals is a result of the battery only having 23 hrs and 10 minutes of continuous battery life while powering the fan. The pseudocode would look something like:

Press bump switch, it turns on the Nano with the ensuing program. Twice an hour, the Nano starts the fan. The fan runs for 20 seconds to 30 seconds each time the fan is started. After a set of 48 on/off cycles have completed (24 hours), the Nano is set to sleep mode in order to save power. In order to restart cycles, user must press bump switch again.

I’m pretty sure I have the hardware side of things down but if I don’t please do inform me.
I’ve attached a picture of what it’ll approximately look like, with the battery at the left, switch in the middle, then the Arduino (not seen in picture), then the fan.

I know this is asking a lot when I don’t even know where to get started with the coding, but I’d be sincerely eternally grateful.

A schematic and some code would be useful to see, although you state that you don't have any code yet...

You can't run the fan directly from an Arduino pin. The fan will require to much current for that to work. Instead connect the fan, via a transistor/mosfet to the Arduino.
Also add a (flyback-)diode to the fan, as turning of the fan can create huge (but short) voltage spikes, which can damage the transistor/mosfet.
Pseudo code would be something like:
for( byte i=0; i<48; i++ )
{
  digitalWrite(fanPin, HIGH);
  delay(20000);
  digitalWrite(fanPin, LOW);
  delay(1780000);
}

You could also put the Arduino in sleep mode, during those half hours, as well. You could use the LowPowerSleep library. Then replace the delay(ms) with LowPower.sleep(ms).
Lastly, some powerbank will automatically shut down, if the detect nothing is using power. The Arduino, without the fan on, will use so little current (compared to charging a phone) that such a powerbank would shut of.

Decent answer, although using delay is teaching bad habits that will need to be unlearned almost immediately. (To the OP, the delay() function causes your app to freeze, so if you need to write code that does something else in a delay function. Better to use the millis() function and some math to record the start time of an event, and check to see when the desired amount of time has elapsed. Search on "Arduino blink without delay" to find sample code explaining the technique.


text:
Noise when running Arduino close to analogue audio circuit
TL;DR: My Arduino is injecting a lot of noise into an analogue audio circuit, even when not physically connected.
I'm experimenting with using an Arduino as a low-frequency oscillator in audio circuits (modular synths, guitar effects etc).  I'm using an Arduino Uno powered with a USB + mains plug.
As a test I set up a simple circuit -- I don't believe the circuit matters much in this case but I'm including it here anyway:

simulate this circuit – Schematic created using CircuitLab
The Arduino is set up with one PWM pin supplying 0-5v, varying in a triangle wave (i.e. ramping slowly up, then slowly down again). This is connected to the JFET, which acts as a variable resistor. I have tested the analogue part of the circuit manually and it works as expected.
With the Arduino connected, however, the circuit produces a very loud "squishing" noise that swamps the audio signal passing through it, not unlike someone tuning an old short-wave radio. The noise "squishes" in time to the oscillation of the voltage.  It's not unlike the sound in this video associated with the PC power supply: https://youtu.be/lXPJvSU8MwI?t=10m52s.
This happens even if I physically disconnect the PWM pin from the circuit -- the closer its wire is to the circuit, the louder the noise, but it's clearly audible even when they're separated by are a foot or more of air.
Things I've tried:

Tying the Arduino ground to the analogue circuit ground, and also keeping them separate.
Adding power filtering caps to both circuits.
Putting the Arduino in an aluminium box, grounded to either its own ground or the analogue circuit's, or both.
Powering the Arduino from my laptop instead of plugged directly into the mains.

The analogue circuit is on breadboard right now so some noise is expected, but this is far outside anything I've experienced before even with very badly-behaved circuits.
I'm FAR from knowledgeable about Arduino so my hope is that I'm doing something stupid and easily fixed. I would happily accept an answer that proposes an entirely different way to achieve the desired result.

you can't make a triangel wave with pwm. it is always squares. a train of squares with different lengths of 0 and 1 level

@Juraj Fair point but I don't think the difference is material in this case, right? It fades an LED as if it were a varying DC voltage (I confess I don't really understand why this works, though).

a led can be fooled to act as it is a continuous voltage. a transistor can't

@Juraj That's very interesting -- so I guess I'd need to replace my FET with an LED/LDR combo. Thanks for enlightening me! Sadly the noise problem would still be a deal-breaker though.

use a DA converter module

@Juraj A LED can't be fooled by PWM, your eyes can. You simply stop seeing blinking past ~100Hz frequency.

@Juraj Because it's turned on half of the time.

The audio output is an AC signal. So it’s voltage will be below GND for about half the time. Are you sure you can use a JFET to switch negative voltages?

@Gerben Yes, I believe it's only shunting the +ve side of the audio to ground. Gives an audible result though -- good enough for a test (this circuit isn't the end product of course!)

Arduino PWM signal is about 500Hz, so it will be audible (read: noise) by itself. You could implement a low-pass filter between the PWM pin and your J-FET. A simple RC filter tuned to 5Hz would attenuate a 500Hz signal to -40dB, which probably won't be enough for high quality audio. There are filters with better rejection properties which usually require active components to build. One of the simplest of such filters is the Sallen-Key topology, which can practically double the rejection ratio using a signle active component (opamp).
Another option is to use a simple RC filter, but increase the the PWM frequency (as described here) to achieve high rejection ratio. Eventually, increasing the frequency past the audible range (about 16kHz) will ultimately resolve the noise problem, though I would still use an RC filter to keep the J-FET in linear mode. Apparently, the highest frequency you can achieve at full resolution is 62.5KHz, which is more than enough.

Thanks for this suggestion. I'll try pushing the PWM frequency up above the audio range and see what effect that has. I suspect a filter on the input won't help as the noise seems to be radiated rather than limited to the circuit itself, but it can't hurt (and is probably good design practice anyway). I'll report back -- it may be later in the week before I get a chance to try it.

@helveticat Noise is "radiated" as long as you allow the J-FET to pick it up by leaving the gate floating. The filter will tie the gate to ground (via a capacitor), and it won't pick anything. Having the gate connected to the Arduino pin will also eliminate noise which is external to the circuit.

I had a chance to quickly try the RC network idea and got significant improvements, with both this and an LED/LDR combination replacing the JFET. Thanks for helping me out!


text:
What is xrotor micro 30A?
I was watching a video on how to build your own drone and this is one of the items. I tried to understand what it actually does but I couldn´t find any simple information.
I would like to know:
- what it does and
- if it could be replaced by an arduino
Thanks !!
Here is the video:
https://www.youtube.com/watch?v=bQib0sAhUc4

What video?  I'm sure some contact would help.

this one https://www.youtube.com/watch?v=bQib0sAhUc4

And where in the video does it talk about this thing?  Do I have to watch the whole 16 minutes to help you?  I don't want to do that.  Please be a little considerate here.

Ok, don't help me then. Is that simple haha

Why don't you add a time stamp to the link, to set the video playing from exactly the correct point? You add &t=XXX to the end of the URL. Where XXX is the time in seconds. It's quite simple, and it would help people who have the same issue, from having to watch the whole video.

The XROTOR MICRO is an ESC, which means Electronic Speed Control. It is essentially the motor driver in a quadcopter. Most quadcopter use brushless motors, because they are more fitted for the fast speeds of the propeller. But brushless motors aren't as easy to drive as simple DC motors. The current through the different coils has to be commutated depending on the current speed of the motor. The ESC does this for you and takes a PWM wave as input, whose duty cycle marks the requested speed. 30A is the current specification for this ESC. For more information google brushless motor.

if it could be replaced by an arduino

Short answer: No.
Long answer: An ESC is a highly specialized device, which is very fast and drives high currents. It may be possible to build something like an ESC with an Arduino in it's heart, but this would be a dumb way to waste your time. The Arduino would be busy controlling the motor, so that it would not be able to do anything else. If you look at how many different peripherals the Arduino embodies, this is a total waste. Also the Arduino cannot drive these high currents by itself. You would have to add extra components to do this. If you are able to build this, it would be much bigger than a normal ESC.
All in all: If you aren't a crack in electronics and want to try this just for achieving, then you should simply buy an ESC for your drone project. Mostly Arduinos have vanished from modern drones, because there are many boards, that are better fitted for this.

Thanks you very much for that very complete answer! I appreciate it Chris !


text:
Why does reading an analog pin give a different results when interfacing with Processing?
I am interested in measuring the voltage over an analog pin (A6). When I use the Arduino IDE to print the results through the serial I get values around 300.
Here's the code
void setup(){
   Serial.begin(57600);
}

void loop(){
   Serial.println(analogRead(A6));
   delay(50);
}

When I try to run a equivalent program using Processing and interfacing it through Firmata and the corresponding library, I get values around 900.
Here's the Processing code:
import cc.arduino.*;
import processing.serial.*;

Arduino arduino;

void setup(){
   arduino = new Arduino(this,Arduino.list()[0], 57600);
   delay(2000);
}

void draw(){
  System.out.println(arduino.analogRead(6));
  delay(50);
}

Does anybody know what could be the issue? I should probably rather trust the values given directly by the Arduino without interfacing, right?
The pin is connected to a circuit with supply voltage.
I also tried reading the values directly using Serial in Processing (so without using the cc.arduino.* - library) and that showed me the values around 300. So I guess the difference is caused by the arduino.analogRead() method. I am puzzled as to whether that's a bug in the library or something else.
The problem seems to be me not properly initialising the pins. But calling
arduino.pinMode(6,Arduino.ANALOG);

in the setup method does nothing, as does Arduino.PWM, SERVO and any combination I tried. I thought, maybe Processing tried to assign D6 as analog instead of A6, but changing the value to 20 (as it's the pin number according to this) simply caused an OutOfBoundsException.

what is connected to the pin?

Have you measured the value on the pin with a voltmeter?

@Craig noup, good idea. Will try that later when I can acces a voltmeter.

You have not provided a schematic of how the Arduino is wired up.
However, if nothing is connected to the pin, i.e. it is not connected to ground or a supply voltage, then the input will float. That means that just by placing your hand near the Arduino, then analogRead() will produce a different value than when your hand in not near it.
I would hazard a guess that if you ran both sets of code multiple times then you will get different answers each time, if you start waving your hand around the Arduino.
Try that first, and then tie the input to either HIGH or LOW and then repeat the previous experiment.
In the second case the results should be consistent, and equal in the Arduino and Processing alike.

However, according to your comment, that is not your issue, as your inputs are not floating.
I think that issue is actually this:

Even with Firmata installed, the Processing application needs to define the pin mode for ALL the pins being referenced, telling the Arduino instance that xPin, yPin, and zPin are ANALOG pins.

Source: Re: Firmata problem with analogRead in Processing Library
Looking at your Processing code the pins are not defined. You need to do so.
With the Arduino code, there is no need to define the analogue pins.

Sorry, forgot to mention: it is connected to a circuit with supply voltage. The values are actually relatively stable around either 900 or 300.

@JorgeAndresQuinteroSerna -  Ah, that is strange then... I strongly suggest that you edit your question and put that information in your original post, to save people having to search around in comments to find it..

@JorgeAndresQuinteroSerna - updated answer with possible reason.

Thank a lot for your help! Unfortunately, I am still not able to properly initialise the pins or that still doesn't fix the issue.

@JorgeAndresQuinteroSerna - oh really? That is a shame. If I find a different solution, I'll try to update my answer. Otherwise if you find a solution yourself, don't forget to post it as your own answer as it will probably help others with the same issue.

Is this solved or not? The answer is accepted, but the comments indicate that it is not solved.

@Juraj - I am not sure. It is probably better to ask the OP. He may have got it working by now (with or without my proposed solution).


text:
What is the cheapest way to add wifi to Arduino?
I am trying to find some sort of wifi adapter for Arduino, it needs to be as small as possible (not a shield) and as cheap as possible.
So far I can only seem to find shields that cost about £10+ but I figured that if you can get a replacement wifi adapter for a laptop for next to nothing that I should be able to get a wifi adapter for Arduino much cheaper than this.
It's possible I just don't know what to search for.

The most cost effective solution is likely not to use a literal Arduino, but rather to utilize something else source-compatible which either has wifi built in, or can host a cheap USB wifi dongle.  It's not entirely out of the question that such a solution, complete, could cost less than a genuine Arduino UNO - and provide a lot more memory and compute resources to work with.

Some months have passed since my previous answer and now the ESP8266 based WiFi modules are available.
They get connected to your project serially (3.3V) and are controlled in a modem like way using AT commands.
With a pricing of round about $5 they fit the question better than my previous OpenWrt based answer.
For more information about ESP8266 ask your favorite finding machine or list news with tag ESP8266 at Hackaday.

(Old answer from the pre-ESP8266-days:)
I vote for a small router reflashed with OpenWrt like "TP-Link TL-WR703N".
It is like building an own Yùn with an Arduino of your choice...
The WR703N:
It has Ethernet, 150MBit WiFi, USB and if you want to solder, a serial console and 2 GPIO-Pins which can be turned into I2C.
This sure is not a chip- or stamp-sized solution but often cheaper than the alternatives, more powerfull and extendable.
Search the net with your favourite find'o'bot for "arduino wr703n" and you'll find lots of examples...

I've seen it somewhere where they use the I2C for direct connection. This would be slower than direct ethernet, but it reduces costs and size without another ethernet chip

The easiest way to connect an Arduino to a WR703N is serial via USB.

The question was asking for "as small as possible, not a shield" and "less than £10". This isn't it.

@FedericoFissore ... The WR703N in fact is one of the cheapest ways to bring WiFi and Arduino together. It is not my fault if someone dreams to use nonexistent mucht cheaper solutions.

Ok... now we have the ESP8266 based modules to add WiFI to your projects... ak your favourite finding machine or http://hackaday.com/tag/esp8266 ...

The Roving Networks RN-XV WiFly module (found sold at €30) might be a solution. I've never tried it. It supports 802.11b/g.

Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.

The question was asking for less than £10. This isn't it.

https://www.forward.com.au/pfod/CheapWifiShield/index.html
provides a very inexpensive wifi addon for Arduino

The WiFi Shield needs just two parts, 4 bits of wire and some soldering equipment. Parts List:-
Adafruit HUZZAH ESP8266 Breakout US$9.95 + shipping
Uno Protoshield US$1.88 + shipping
Total US$11.83 (as of June 2015)
For an even cheaper version ~US7 see https://www.forward.com.au/pfod/CheapWifiShield/ESP2866_01_WiFi_Shield/index.html
Both of these need a US10 USB to TTL cable to program them
After you have installed the pfodESP8266BufferedClient library, open the Arduino IDE and copy this sketch, ESP8266_WifiShield.ino, into the IDE.
That provides this setup webpage.

While that link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

Please disclose your affiliation, you appear to be the author of the site you've linked multiple times.

Sure I will add a 'my' to future posts.

Texas Instruments CC3000 module 10USD/1000pcs, it does only support connecting to AP, i.e. no AdHoc/AP which is useless for direct using with iPad.