I've been working on a project and I get an error compiling for board arduino uno. kindly help ##include <jm_LiquidCrystal_I2C.h>

#include <LiquidCrystal.h>

#include <Wire.h> // For I2C
//Set the pins on the I2C chip used for LCD connections
//ADDR,EN,R/W,RS,D4,D5,D6,D7
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7); // 0x27 is the default I2C bus address of the backpack-see article

#define echoPin 3 // Echo Pin (OUTPUT pin in RB URF02)
#define trigPin 2 // Trigger Pin (INPUT pin in RB URF02)

int led = 5;
int maximumRange = 350; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance
int brightness;

void setup() {
  lcd.begin (16, 2); // 16 x 2 LCD module
  lcd.setBacklightPin(3, POSITIVE); // BL, BL_POL
  lcd.setBacklight(HIGH);
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  // The following trigPin/echoPin cycle is used to determine the distance of the nearest object by bouncing soundwaves off of it.
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration / 58, 2; //Calculate the distance (in cm) based on the speed of sound.
  lcd.home (); // Set cursor to 0,0
  lcd.print("The Water Level is");
  lcd.setCursor (0, 1);
  lcd.print(distance); // Custom text
  lcd.print("cm");
  Serial.println(distance); // distance in cm
  brightness = map(distance, 1, 100, 0, 255);
  analogWrite(led, brightness);
  delay(1000); //Delay 50 ms

#include <LcdKeypad.h>

#include <LiquidCrystal.h>

#include <Wire.h> // For I2C
//Set the pins on the I2C chip used for LCD connections
//ADDR,EN,R/W,RS,D4,D5,D6,D7
LcdKeypad lcd(0x3f, 2, 1, 0, 4, 5, 6, 7); // 0x27 is the default I2C bus address of the backpack-see article

#define echoPin 3 // Echo Pin (OUTPUT pin in RB URF02)
#define trigPin 2 // Trigger Pin (INPUT pin in RB URF02)

int led = 5;
int maximumRange = 350; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance
int brightness;

void setup() {
  lcd.begin (16, 2); // 16 x 2 LCD module
  lcd.setBackLightOn(3); // BL, BL_POL
  lcd.setBacklight(HIGH);
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration / 58, 2; //Calculate the distance (in cm) based on the speed of sound.
  lcd.home ();
  lcd.print("The Water Level is");
  lcd.setCursor (0, 1);
  lcd.print(distance);
  lcd.print("cm");
  Serial.println(distance);
  brightness = map(distance, 1, 100, 0, 255);
  analogWrite(led, brightness);
  delay(1000);
}


NodeMCU ESP8266 Ver 0.1 not powering on with VIN I'm trying to power on my NodeMCU ESP8266 Ver 0.1 (thats what is written in board), via VIN and Ground with my phone charger.
I'm 100% sure that the USB charger is working, providing 5V, and that the ground and VIN are connected to the right positions.
If I use the same phone charger via the NodeMCU USB, the program blinks the builtin led alright.
If I power via VIN, it flashes when I connect the charger to DC, but the program does not work.
It seems as the NodeMCU is not powering on complety.
Bizarrely, if I short 3V and G pins, the board starts working normally as powered directly via USB port.
This is the code
/*
 ESP8266 Blink by Simon Peter
 Blink the blue LED on the ESP-01 module
 This example code is in the public domain

 The blue LED on the ESP-01 module is connected to GPIO1
 (which is also the TXD pin; so we cannot use Serial.print() at the same time)

 Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

Interesting problem. The input range for Vin is 5.5 to 10 volts. This link will give you more information: https://www.make-it.ca/nodemcu-arduino/nodemcu-details-specifications/
I would not venture to guess that your board is OK, since you short pins all kinds of nasties can happen. Also you do not state your reference point for your voltage measurements so I assume it is ground but the readings do not appear correct. How are you 100% sure that the USB charger is working, providing 5V, and that the ground and VIN are connected to the right positions. Did you measure it with the load connected? Can the charger output the voltage at the current you require?


Convert long to char array and back I'm trying to store a state in my data logger. I can read/write fine to SD, but I can't wrap my head around reading/writing a long value correctly - I've build it down to converting it to char array and back.

My best try so far has been

long temp = 1418172669L;
unsigned char buf[4];
buf[0] = temp         & 0xFF;
buf[1] = (temp >>  8) & 0xFF;
buf[2] = (temp >> 16) & 0xFF;
buf[3] = (temp >> 24) & 0xFF;

long  l = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

But l is very different from temp - currently the output is -26371. Am I making an obvious mistake?

I suggest using a union:

union {
    char myByte[4];
    long mylong;
} foo;

Char to Long:

Then you can just add the bytes:

foo myUnion;
myUnion.myByte[0] = buf[0];
myUnion.myByte[1] = buf[1];
myUnion.myByte[2] = buf[2];
myUnion.myByte[3] = buf[3];

Then you can access the long as:

myUnion.myLong;

Long to Char:

The same if you want to go the other way from long to char array:

foo myUnion
myUnion.myLong = 1234L;

To access bytes:

myUnion.myByte[0];
myUnion.myByte[1];
myUnion.myByte[2];
myUnion.myByte[3];

char text[5];
long number = 1234;
sprintf(text,"%d",number);


String compare when using Serial I try to detect commands given by user in Serial Monitor, but strcmp fails to flag as identical.

What do I do wrong ?

Is there a better way not reading as String and convert to char for comparison ?

Guy

char* additional_callbacks [] = {"command_1", "command_2", "command_3"};

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

void loop() {
  if (Serial.available() > 0) {
    char tmpchar[50];

    Serial.print("entered_text:");
    String str = Serial.readString();
    str.toCharArray(tmpchar, 50);
    Serial.println(tmpchar);

    for (int i = 0; i < sizeof(additional_callbacks) / sizeof(char*); i++) {
      if (strcmp(tmpchar, additional_callbacks[i]) == 0) {
        Serial.println("match");
      }
    }
    Serial.flush();
  }
  delay(50);
}

In your for() loop, use Serial.println() to display both strings before the compare. You'll be able to see why the compare is failing.

Update:

  it seemed identical.

Something has to be different for the test to fail. If the strings look identical then there must be some non-printing characters that differ: \r, \n, , , missing \0 ), etc.

Try printing your buffers byte-by-byte in hex for a few more bytes than the string length, to be sure there is an  where it should be.

Or print the buffers with this hexdump function which lists a specified memory range in both ASCII and hex:

/***

Name:       hexdump

Function:   Dump memory contents to terminal

Description:Dump a specified range of memory in hex and ASCII

Parameters: byte *mem       - starting address
            uint16_t len    - # of bytes

Returns:    void

Notes:      Based on: http://grapsus.net/blog/post/Hexadecimal-dump-in-C
            Formats with sprintf(); outputs with Serial.print().
            Modified to print ...0 - ...F of each hex-block containing
            any of the requested memory range. Data not in the range are
            not shown.

***/

void hexdump(byte *mem, uint16_t len)
{
   byte *p, *pfirst, *plast;    // -> curr byte, first & last hex-blocks to print from
   char buf[10+1];              // sprintf o/p buffer

   // Print entire hex-blocks that contain the requested mem range,
   // except only show data within the range.
   pfirst = (byte *)((uint16_t)mem & 0xFFF0);           // beg of 1st  hex-block
   plast = (byte *)((uint16_t)(mem + len) | 0xF);       // end of last hex-block

   for( p = pfirst;  p <= plast;  ++p ){

      /* Print block addr */
      if( ((byte *)((uint16_t)p & 0xF)) == 0 ){
         sprintf_P(buf, PSTR("%06X: "), (unsigned int)p);
         Serial.print(buf);
      }

      // Print hex data, or if outside mem range, print spaces
      if( mem <= p && p < (mem + len) ){
         sprintf_P(buf, PSTR("%02hhX "), *p);
         Serial.print(buf);
      }
      else
         Serial.print("   ");                   // outside requested range - just spaces

      // Maybe print gutters and/or ASCII data
      if( ((uint16_t)p & 0xF) == 0x7 )
         Serial.print(" ");                     // narrow gutter after 8 bytes
      // If at end of hex block, print a gutter & re-print the block as ASCII
      if( ((uint16_t)p & 0xF) == 0xF ){
         Serial.print("  ");                    // wide gutter after 16 bytes

         // Print as ASCII.
         // Note: In this loop, we re-use the outer loop's index, 'p', to rescan
         // the hex block. We must leave 'p' as we found it!
         for( p = (byte *)((uint16_t)p & 0xFFF0);  ; ++p ){
            if( !(mem <= p && p < mem+len) )
               Serial.print(' ');               // not in requested mem range
            else if( !isprint(*p) )
               Serial.print('.');               // not printable
            else
               Serial.print(*(char *)p);        // print as ASCII

            if( ((uint16_t)p & 0xF) == 0xF ){
               break;                           // end of hex-block
            }
         }
         Serial.print('\n');
      }
   }
}

You try to compare Serial input

  command_1\r\n

with

  command_1

and these two are not equal.


Nodemcu stops sending the messages to the API Here is my code which sends some data to the firebase cloud functions. The code works well and the nodemcu sends the data to the cloud for about half an hour and then stops sending the messages.

#include <OneWire.h>
#include <DallasTemperature.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

#define ONE_WIRE_BUS 5

// Use WiFiClientSecure class to create TLS connection
WiFiClientSecure client;

OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);
String data="";
const char* ssid = "***************";
const char* password = "**************";

const char* host = "**************************";
const int httpsPort = 443;

String url = "/getData";
float Celcius=0;
float Fahrenheit=0;
int sensor_light;
int sensor_temp;
int sensor_moist;
void setup() {
ESP.wdtDisable();
pinMode(16,OUTPUT);//moist
pinMode(0,OUTPUT);//light
Serial.begin(115200);  //Serial connection
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

Serial.print("connecting to ");
Serial.println(host);
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
ESP.wdtEnable(WDTO_8S);
}
void loop()
{
 client.connect(host, httpsPort);
 int l,m,t;
 data=" ";
 l=get_light();
 t=get_temp();
 m=get_moist();
 if(WiFi.status()== WL_CONNECTED){
    data+="{";
    data+="\"";
    data+="Node-Id";
    data+="\"";
    data+=":";
    data+=1;
    data+=",";
    data+="\"";
    data+="light";
    data+="\"";
    data+=":";
    data+=l;
    data+=",";
    data+="\"";
    data+="temperature";
    data+="\"";
    data+=":";
    data+=t;
    data+=",";
    data+="\"";
    data+="humidity";
    data+="\"";
    data+=":";
    data+=m;
    data+=",";
    data+="\"";
    data+="Latitude";
    data+="\"";
    data+=":";
    data+=29.3589362;
    data+=",";
    data+="\"";
    data+="Longitude";
    data+="\"";
    data+=":";
    data+=79.5506528;
    data+="} ";
    Serial.println(data);
    client.print(String("POST ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n"+
           "Content-Length: " + data.length()+ "\r\n" +
           "Content-Type: application/json;charset=UTF-8\r\n\r\n"+
            data +"\r\n");
    //  Serial.println("Sent");
    String line = client.readStringUntil('\n');
    Serial.println(line);
    while(!client.connected())
        { client.stop();
          ESP.wdtFeed();
         }
     }
    delay(4000);
    }

    int get_light()
    {
    digitalWrite(0, HIGH);
    sensor_light=0;
    sensor_light = analogRead(A0);
    digitalWrite(0, LOW);
    delay(2000);
    return sensor_light;
    }
    int get_temp()
    {
    int  sum=0,i;
    for(i=0;i<10;i++)
      {
    sensors.requestTemperatures();
    Celcius=sensors.getTempCByIndex(0);
    delay(250);
    sum+=Celcius;
    }
    Celcius=sum/20;
    delay(2000);
    return Celcius;
    }

    int get_moist()
    {
     digitalWrite(16, HIGH);
    sensor_moist=0;
    sensor_moist = analogRead(A0);
    digitalWrite(16, LOW);
    delay(2000);
    return sensor_moist;
    }

If I do not use ESP.wdtFeed() and other similar functions then I am getting Soft wdt reset error. I am using the laptop to power it. Any help?

Remove the return in setup function and check. And set regular yield () statements to ensure smooth running of background tasks. And use if statement in the loop for !client.connected()


Sending digital signal from one arduino to another I have one arduino with two proximity sensors that send two digitalWrite signals if an object is detected. I checked to make sure the output of these is working properly and only sending high signals when they should. I have a second arduino that is wired directly from those two outputs as two digitalReads and printing whether or not they are high or low.

The problem is that even though the first arduino is not sending a high signal, the second arduino's digitalReads are seeing high. I tried putting a 1k or 10k resistor in between and that just seemed to decrease the rate of this happening, but it also decreased the rate of seeing the high signal when there actually was one.

Anybody know what I'm doing wrong?

Connections:

Arduino 2 (sensors) code:

/* Two ultrasonic sensors for collision detection
Angled on front sides

Checks for object and sends digital high if distance is less than set threshold
(ran out of pwm pins on main arduino)
*/

#define LEFT_INPUT 5
#define RIGHT_INPUT 6
#define LEFT_OUTPUT 8
#define RIGHT_OUTPUT 9

// distance to stop
int stopThreshold = 24;  // ~10cm

// vars
long ultraLeft, inchesLeft, cmLeft;
long ultraRight, inchesRight, cmRight;
int objectDetectedLeft, objectDetectedRight;

void Poll_Ultrasonic()
{
  // left
  ultraLeft = pulseIn(LEFT_INPUT, HIGH);
  inchesLeft = ultraLeft / 147;
  cmLeft = inchesLeft * 2.54;
  if (cmLeft < stopThreshold)
    objectDetectedLeft = 1;
  else
    objectDetectedLeft = 0;

  // right
  ultraRight = pulseIn(RIGHT_INPUT, HIGH);
  inchesRight = ultraRight / 147;
  cmRight = inchesRight * 2.54;
  if (cmRight < stopThreshold)
    objectDetectedRight = 1;
  else
    objectDetectedRight = 0;
}

void setup()
{
    // Serial monitor
  Serial.begin(9600);
  // pins
  pinMode(LEFT_INPUT, INPUT);
  pinMode(RIGHT_INPUT, INPUT);
  pinMode(LEFT_OUTPUT, OUTPUT);
  pinMode(RIGHT_OUTPUT, OUTPUT);
}

void loop()
{
  // check distances, set flags
  Poll_Ultrasonic();

  // set output pins high on detection, print detection messages
  if (objectDetectedLeft) {
    digitalWrite(LEFT_OUTPUT, HIGH);
    Serial.println("\n  LEFT object detected!\n");
  }
  else
    digitalWrite(LEFT_OUTPUT, LOW);

  if (objectDetectedRight) {
    digitalWrite(RIGHT_OUTPUT, HIGH);
    Serial.println("\n  RIGHT object detected!\n");
  }
  else
    digitalWrite(RIGHT_OUTPUT, LOW);

  // print distances
  Serial.print("Left ultrasonic distance: ");
  Serial.print(cmLeft);
  Serial.println("cm");
  Serial.print("Right ultrasonic distance: ");
  Serial.print(cmRight);
  Serial.println("cm");
}

Arduino 1 (main) code snippet:

// Ultrasonic pins
#define ULTRA_LEFT 7
#define ULTRA_RIGHT 11

// Ultrasonics
pinMode(ULTRA_LEFT, INPUT);
pinMode(ULTRA_RIGHT, INPUT);

void Poll_Ultrasonic()
{
  if(digitalRead(ULTRA_LEFT) && digitalRead(ULTRA_RIGHT))
    leftOrRight = 2;
  else if (digitalRead(ULTRA_LEFT))
    leftOrRight = -1;
  else if (digitalRead(ULTRA_RIGHT))
    leftOrRight = 1;
  else
    leftOrRight = 0;

  if (leftOrRight)
    objectDetected = 1;
  else
    objectDetected = 0;
}

...

void StopCar()
{
  esc.write(90);
  if (leftOrRight == -1)
    Serial.println("Object detected on LEFT! Stopping.");
  else if (leftOrRight == 1)
    Serial.println("Object detected on RIGHT! Stopping.");
  else if (leftOrRight == 2)
    Serial.println("Object detected on BOTH! Stopping.");
  else // should never reach this
    Serial.println("Ultrasonic debug statement: bad condition");
}

OK , start by connecting an LED at the Output of Arduino 2 pins .. ( hopefully it will glow )

Measure the current out of the output pins of Arduino 2 too


ESP32 runtime error in 2d array I am trying to serial print the value of b[0][0].

Has to be zero but it dose not work!

Here is the code

void setup() {
  Serial.begin(115200);
  byte b[321][241];
  Serial.println(b[0][0]);
}

void loop() {

}

If the array is small like b[2][2] it dose work

In theory esp32 has ram of  520 KiB SRAM so can this be a problem?

Here is the error code

rst:0x8 (TG1WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8

The code complies fine but the error gets when esp32 is running

esp32 version for arduino is 1.0.4

The ESP32 uses FreeRTOS to run everything, and that includes the Arduino API. Your code is running in a thread of its own ("loopTask"), and that task by default has 8192 bytes of stack allocated to it.

xTaskCreateUniversal(loopTask, "loopTask", 8192, NULL, 1, &loopTaskHandle, CONFIG_ARDUINO_RUNNING_CORE);

You cannot create local variables and other stack data that totals more than 8192 bytes.

Instead you will either have to have the variable as a global variable (or static local) so it gets allocated in the global data segment, or use new or malloc to create it on the heap (and don't forget the corresponding delete or free call when you're done with it).

This may be due to serial buffer size.
ESP32 may wrire new data before finshing previous transfer. Add a delay after print line and see.


How can I have different routines fire off at different intervals So i'm making an interface that will have a digital clock....once a secondd..
i'd like to do other things at different intervals but if I delay(1000) then I have to wait that second which is now the minimum other things have to run at..

As said in the comments: you should read up on State Machines and have a close look at the Blink Without Delay example.
To get you started with an example closer to what you want to achieve, have a look at the code below; it will count seconds without blocking the loop.
unsigned long int secondsTimerMillis;
int seconds, minutes, hours = 0;
int secondsInterval = 1000; //ms

void setup() {
  Serial.begin(9600);
  // More setup() stuff goes here
  secondsTimerMillis = 0;
}

void loop() {
  if ((millis() - secondsTimerMillis) >= secondsInterval) {
    seconds++;
    secondsTimerMillis = millis();
    Serial.println(seconds);
    // More stuff you want to do every second goes here
  }
  // More loop() stuff goes here
}

This is just the basic mechanism, and it won't be very accurate without some way of adjusting the clock every now and again.
You will also have to add code for checking seconds == 60 and increase minutes / reset seconds when needed; the same goes for hours.
Having/handling other events at other intervals is just more of the same.
Note that using a Real Time Clock as the basis for your timing would make your life programming much easier, and your clock more accurate, but I am assuming you want to do this "by hand".

The short answer, to keep in mind while studying the above suggested reading, is to run your timer faster, maybe delay(1) or delay(10) or whatever is fast enough to service your other functions, then just make the "clock" be one of those functions that counts up the total small delays to get your 1 second delay.  This assumes that your other functions don't take too much time to run, which will throw off the 1-sec timing count.  So a better way than a simple count is to have the clock function read the current time and compare to the start time. When it reaches 1 second, you set a new start time.


Run two Loops Simultaneously on Arduino I am not able to combine the below two sketches. What I require is to either run both the loops together or find a way to run both the functions inside a single loop.

Sketch 1

#include <SevSeg.h>
#include <DS1307RTC.h>
#include <Time.h>
#include <TimeLib.h>
#include <Wire.h>

// Create an instance of the object
SevSeg sevseg;
bool militaryTime = false; // true for 24 hour clock

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {2, 3, 4, 5};
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_ANODE; // See README.md for options
  bool updateWithDelays = false; // Default. Recommended
  bool leadingZeros = true; // Use 'true' if you'd like to keep the leading zeros

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments, updateWithDelays, leadingZeros);
  sevseg.setBrightness(90);
}

void loop() {
  tmElements_t tm;
  int time;
  int dot;

  if (RTC.read(tm)) {
    time = tm.Hour * 100;
    if (time > 1200 && militaryTime == false) {
      time = time - 1200;
    }
    if (time == 0 && militaryTime == false) {
      time = 1200;
    }
    time += tm.Minute;
  }

  if ((tm.Second % 2) == 0) {
    dot = 4;
  } else {
    dot = 2;
  }

  //Produce an output on the display
  sevseg.refreshDisplay();
  sevseg.setNumber(time, dot);
}

Sketch 2

// Change this to the output pin you are using
#define TICK_PIN A0

void setup()
{
  pinMode(TICK_PIN,OUTPUT);
  while (1) {
    tone(TICK_PIN,1000,2);
    delay(1000);
  }
}

void loop()
{
}

Basically you need to get rid of the delay and any other blocking loops. Here is a way to do it.

Define this variable globally.

unsigned long lastTime = 0;

Then in your first loop, add the following code either to the beginning or the end:

if (millis() - lastTime >= 1000 || !lastTime) {
    lastTime = millis();
    tone(TICK_PIN,1000,2);
}

Run two Loops Simultaneously on Arduino

in general, the answer depends on your definition of "simultaneously".

But in this case, the answer is "definitively yes", as the other loop is empty.

a generic approach to this kind of questions is:

void setup(void) {
  setup1();  //run setup 1
  setup2();  //run setup 2
  ...
}

void loop(void) {
  loop1();  //run loop1
  loop2();  //run loop2
  ...
}

this approach would only fail if the original setup() and loop() are written poorly.


How to track revolution of DC motor? I am currently trying to build a line follower robot that is designed to solve maze. This maze has a loop, thus it needs to know distance it already travelling (or at least I assume so, please let me know otherwise).

I am aware of a rotary encoder motor from Polulu (for example) but it's not available in my country and shipping price is too expensive.

So I need to find way around it. Should I use Stepper motor? Is there any other way? Thanks in advance.

You can Use wheel encoders. You can even make your own wheel encoders with general parts like photoTransistor and lasor or led light. you can make your encoder or print it out in paper. The use little math to calculate the distance. It will give you measurement with good level of precision.

Basic principle:

more information at

wheel Encoder

another encoder

SInce you mention cost is an issue. The cheapest way to do it is simply to track how much time the motor (which can be done by using arduino timer libraries)-is running for backwards or fowards in some direction. Given you know the speed of the robot it then using the formula

velocity=(distince in some direction from 2D vector)/(time motor is running for in that direction)

from which distance can be deduced. This assumes there is low error bound in this formula-and the velocity is constant-and the robot never leaves the flat floor--and so its accuracy would depend on the specifics of the question- Using a stepper motor would very much increase the accuracy-if it has enough steps then the error would be non-significant- using that formula. You may need to store-a non solved-internal map of the maze in an arduino sketch (for determining the direction and so on). You can use the same answer above for variable velocity given you know when the times of velocity change. would make if you give me more info I can give more of an answer.


code wont upload to arduino starter kit My operating system : OS X EL CAPITAN

Please help I was trying to do project 05 Mood cue of the arduino starter kit. I completed setting up my board and writing the code and when I tried to upload I got this error message:

Arduino: 1.7.10 (Mac OS X), Board: "Arduino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/tty.usbmodem1411": Device not         configured
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

Can someone please help me?

Thank you Harry i managed to fix it by downloading CH341SER_MAC.zip just in case someone has the same problem wch.cn/downfile/178


What is the most efficient voltage divider for Arduino? I need to make voltage divider, so I could read a battery voltage up to 14.4 V. Could I use very high resistance resistors for that, so the current would be very low (to not to discharge battery)?
On the Internet there are examples with 500 - 2000 ohm resistors, but could I use hundreds of thousands to reduce the current to minimum? Would Arduino's analog input still read the value?

The most efficient is not to have a voltage divider at all. Or at least to only have a voltage divider when you actually need one.
My preferred schematic is this:

simulate this circuit – Schematic created using CircuitLab
With this M1 is normally kept turned off by R3. When you want to take a measurement you turn on M2 by setting D3 HIGH (or whatever pin you attached it to) which pulls down the gate of M1 turning it on. This then connects the batter to the voltage divider R1/R2 and allows you to read the voltage at A0.
The voltage divider of 20k / 10k allows you to read up to 15V on the battery, and gives you an output impedance of 6.67kΩ which is within the recommended maximum of 10kΩ for the ATMega's ADC.
During "idle" times when M1 and M2 are both off the only current flowing is the minuscule leakage current through M2 tempered by the large 100kΩ resistor R3 (which itself pales into insignificance compared to the "off" resistance of M2 anyway).
Selecting M1 so that the ON resistance is very small (<0.1Ω) allows you to essentially ignore it in your calculations since that will be swamped by the tolerance of R1 and R2 anyway.  M2 needs to be selected so that it is "logic level" (i.e, with a gate threshold V_GS well below 5V).
This double-FET arrangement should be used rather than just using an N-channel FET in the ground connection of the divider because when that simpler arrangement is turned off the Arduino will be seeing 12V directly connected to A0 which really is not good - you will kill the Arduino - so it is important that you switch the "high" side of the network not the "low" side, and to do that requires two FETs.

I don't see any problem with reasonably high resistors (however see below). You are right that they would discharge the battery less.

Would Arduino's analog input still read the value?

Of course, if there was a voltage there to read. Why wouldn't it? A really high resistance might let the reading be affected by stray voltages.
A possible work-around would be to only take the reading occasionally, say, every 10 seconds. You could do this by making the reading be between a couple of Arduino pins, and leave one "floating" until you are ready to read it.
However that is not a good idea for reading a 12V battery. You need the voltage divider to be "active" so you don't have 12V on the Arduino input pin. Majenko's suggestion sounds better in that respect.
I have a lengthy discussion about the ADC on the Atmega328P. Reply #5 on that page discusses how it takes its measurements. This is done by charging a "sample and hold" capacitor. With too high an input impedance the capacitor would charge too slowly, and thus the subsequent sampling would give incorrect readings. A source signal impedance of 10k is recommended in the datasheet, so a voltage divider along those lines would be appropriate.
Majenko's suggestion of 20k + 10k would only involve a 0.4 mA constant current flow through the voltage divider, which for a 12V battery is probably not a huge deal (even without all that switching circuitry).


A simple login page on Arduino Uno I'm trying to setup home automation system controlled with webpage stored in SD card of Arduino, I was thinking if it was possible to set a login page, only combination of correct user id & password will be able to access the control page.

I have a page about a tiny web server for the Arduino Uno or similar boards. It simply isn't true that you can't make one, or that a much more powerful processor would be better. There are some limitations imposed by small amounts of RAM, but the library described there decodes incoming HTTP information "on the fly" so it can handle a reasonably large page.

You could put the data to be display into PROGMEM (more information here) or onto an SD card as someone suggested.

The login and password could be stored in EEPROM.

I guess you could do it with Javascript and HTML, and put the pages in the micro SD card.

But it will make it harder (if not impossible) to make the automation.


Having a problem to control digital servo with HC-06 bluetooth module There are two problems to control digital servo(HD-1810MG) and HC-06 bluetooth module connection.

When I put a specific number to servo(in the video, I put 45), it shakes too much and shows useless movements before get to the right angle. I have no clue why this happens. Should I add more code to control it correctly?

This is my code.

#include SoftwareSerial.h
#include Servo.h

Servo myServo;
int TxD = 10;
int RxD = 11;
SoftwareSerial bluetooth(TxD, RxD);

void setup() {
  myServo.attach(9);
  Serial.begin(9600);       // start serial communication at 9600bps
  bluetooth.begin(9600);
}

void loop() {
  if (bluetooth.available()>0)
  {
    int servopos = bluetooth.read();
    Serial.println(servopos);
    myServo.write(servopos);
    delay(100);
  }
}

I used Nexus 5X and apk app to pair with HC-06. It pairs well at the first time of connection, but it loose connection after servo moved once. Application said it is connected with bluetooth, but HC-06's LED is blinking(which means disconnected). How can I maintain connection with HC-06?

This is my board.

And I made apk app using MIT App Inventor 2.

I'm so new to arduino and I'm not in major of engineering. Please give me an advice!

let have a look at following line of code:

int servopos = bluetooth.read();

I think that you are thinking that if you type in 1 in your
Bluetooth application. bluetooth.read() will pass that 1 to
sevopos. But, that's what not happens. What actually happens is that it will pass the ASCII value of whatever you type in you
app, to integer. So, if you have typed in 1, it will pass 49
to servopos.

  I put 45

Now, think about it. when you type in 4 of this 45,

bluetooth.available()>0

becomes true.

int servopos = bluetooth.read();

bluetooth.read() will pass 52 (ASCII of 4) to servopos. Next,

myServo.write(servopos);

myservo will move your servo to lets say 52 degrees. and then there will be a delay.

Now, when you type in 5 of this 45, the procedure will be
repeated and your servo will be moved again by 53 degrees.

Now, you might be wondering that why 4 and 5 sepratly? Well,
all these intructution are being executed in MHzs. and secondly,
you, yourself has programmed that if loop you read just once
character. Yes, it will read character by character.

  but it loose connection after servo moved once

I think your servo is drawing too much current from Arduino Board
which results in a drop in net voltage. And hence your HC-05 (kind
of) tuns off. This is what happens most of the time.

It is not a problem in serial connection. I have experienced this problem when I was trying to make a biped robot using 12 servos. It is the programming bug where Arduino does not use its timers properly. You can say that it is arduino limitation.
There are two main solutions :
1). Use Raspberry Pi instead of arduino.
2). Secondly you can make a small servo controlling shield of TLC5940 IC + servo controlling library...  Here is he Link: http://bildr.org/2012/03/servos-tlc5940-arduino/


Running Arduino mega on 5V power supply I'm wondering if I can run Arduino mega on 5V power supply, even though it's recommended for 6-12V. USB has only 5V right, will it be a problem? I expect to draw quite a lot of power from the 5V pin too so could it be a problem?

The 6-12V range applies only to the onboard voltage regulator(if you provide power via Vin or the barrel jack). The Arduino itself runs on 5V and the regulator needs a bit headroom above that to do the regulation.
You can run the Arduino via USB, since it has 5V, just as needed by the Arduino
And you can provide power directly to the 5V pin (with a voltage of 5V or course).
If some of your components draw a lot of power, you should never draw that current through the Arduino. You need to connect the power supply in parallel to your components and the Arduino, so that the high currents can flow past the Arduino, not through it.

No you cant run a Arduino on 5Volt if you feed it via the DC connector without doing some modifications to the Arduino.


Convert uint8_t array to ascii character for serial transmission I am trying to send packets of via bluetooth data that include 6 bytes read from a sensor and stored in a uint8_t array. Instead of sending over the data as numerical digital, I would like to send the ASCII character of each of the bytes. I am doing this to reduce the size of my data packets and make it easier to interpret the incoming data.

uint8_t* temp = readBufferData(FIFO);

for (int i = 0; i < 6; i++)
{
    Serial.write(temp[i]);

}

Read buffer data returns a pointer to a uint8_t array read from a FIFO buffer.
When I use Serial.print, I get the following output, which makes sense.
22163226094255
One question is, when I use Serial.print on a single character, is it transmitted a single byte, or is it actually sending the decimal digital of the number, anywhere from 1-3 bytes?

When I use the Serial.write, however, I get something like the following
DÿÂ?ÁÏ?ÌÆ?Ûµ?Ë½?ÔÀ?Ð¿?ÃÕÓÑËÐTÿÀ?Ï3ÿÉ?¹4ÿÐ?Ê<ÿ½?µfÿ¼?ìNÿÐ?×Â?ÊÚ?×¿?Å
Also, these data display much more slowly on the screen, than normal.

How can I send each uint8_t value by sending over the corresponding ASCII character for serial transmission?

Thanks!

You don't "convert" anything. A character is just a human representation of an 8-bit value.

Instead you just need to change what the compiler thinks the data represents (from a human perspective).  The simplest way of doing that is to either cast the uint8_t values to be char values, or to write each one individually as a raw value.

The latter way:

myBluetoothSerial.write(myData[0]);
myBluetoothSerial.write(myData[1]);
myBluetoothSerial.write(myData[2]);
myBluetoothSerial.write(myData[3]);
myBluetoothSerial.write(myData[4]);
myBluetoothSerial.write(myData[5]);

Or, with a loop:

for (int i = 0; i < 6; i++) {
    myBluetoothSerial.write(myData[i]);
}

or using a built-in variant of write that does the loop for you:

myBluetoothSerial.write(myData, 6);

Try changing Baud Rate. Most of the time garbage like this happens because of difference in baud rates of transmitter serial device and receiver serial device.


Arduino clone avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x04 Hi firstly sorry for my english. I am using windows 10, IDE version 1.8.13. I sure for selected correct arduino(Arduino uno),port is correct, tried another cable. I uploaded sketch 3-5 times but after give this error. I using MAX7219 led matrix shield and shield is working and shown my lastest upload before error. Error:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM6
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x04
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x04
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x04
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x04
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x04
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

Problem not solved, but I can program it with a USBASP programmer. I burned a bootloader, but the USB connection didn't work.
I am now using it without a bootloader.

I would suggest checking if you have selected the correct arduino. If that is correct then check the port to be sure the correct one is selected. If you are using Linux be sure you have permission for dialout. dialout gives you full and direct access to serial ports. Members of this group can reconfigure the modem, dial anywhere, etc. dip: The group's name stands for "Dial-up IP", and membership in dip allows you to use tools like ppp, dip, wvdial, etc. to dial up a connection. At that point I think you might be on your way. If this does not solve the problem lets us know what computer you are using, which OS and of course which version of the IDE you are working with.


Detecting different objects closeness iam currently working on a new project, where i would like to detect the existence/closeness of several objects around the arduino up to like 1 meter. I was thinking about an rfid setup, but as the objects could have different sizes like 5 centimetre tall and only 3 centimetre wide, i think this won't work for the max distance. I was also thinking about a ble beacon, but as this one has to be activley powered all the time, it wouln't be the perfect solution. As the base could be fully customized, it may have some kind of sensors/wires overall the surface, but iam a bit lacking of a good idea for this.
I hope someone might had a similar setup, or a good idea to go.
PS: When i think about it twice, it would be better, if it can be differentiate between some areas within the one meter and the different objects, entering each area. I've added some image, hope this helps to understand, what i want to archive at the end.

Thank you and greetings,
Sebastian

As you might have already seen, a position sensing system can be really complex. Here I will list some possibilities, that come to my mind and might be fitting for your case or not.

Matrix based solutions: Here I mean sensors a some sort arranged in a matrix underneath the game table, which can sense the object placed on them. As you know from your wiring, where a specific sensor is located, you know from the triggered sensor, where the object was placed. The resolution directly corresponds to the numbers of sensors, that you place. You can use different sensors, which will give you different information, but are also very different in handling and costs:

Reed switches and magnets on the bottom of the objects. The magnet on the object would close the reed switch. A read switches are rather cheap (have seen 40 pieces for about 10€ on amazon; on aliexpress or others you might get them even cheaper) and can be easily placed in an electrical matrix or (depending on the number and places of object at any time) checked via shift registers, which are also not very pricey.

Hall sensors and magnets on the bottom of the objects. You would measure the magnetic field of the magnets with the hall sensors. You could use different magnet strengths to get different readings and thus directly distinguish between different object types. The hall sensors will be not that easy to read. Mostly they have an analog output, thus you would need extra ADCs and multiplexers to read them all.

RFID readers and RFID chips in each object. Very pricey and rather low resolution. Also very difficult to read from all of them with the Arduino. But you could go for the reed switch version and use a single RFID reader to first tell the Arduino, which object you are placing. In the game you would first hold the object to the reader, then place it on the board.

Lidar system: A Lidar scanner could scan over your board (it measures the distance in a circle around it). Each object would be a negative peak in the measured distance distribution. From the angle and the distance, you could calculate the position on the board. Though you would need to carefully place the sensor, as one object might hide the other behind it. You can tackle that with an additional Lidar scanner, but the processing will also be rather complex. And Lidar scanners are rather expensive.

Ultrasonic sensors out the board: If you place enough ultrasonic sensors around the board and measure with one after the other, you might also get fitting results. But I would guess, that you won't get good positioning results with them, especially for the rather small objects and distances used on a game table.

Computer Vision: Away from Arduino you could use OpenCV on a Raspberry Pi together with a small camera above your board to detect objects. General object detecting is rather easy with OpenCV and python; getting it's position in the camera image is trivial then (from where you can calculate the position on the board easily). With more work it should also be possible to detect the object themselves (meaning distinguishing between different objects). We might need to train OpenCV with top-down images of the objects for that. If you don't get good results with the normal camera mode, you could try the IR camera mode (by removing the IR filter of the Pi's camera) and put some good IR reflective stuff on the top of the objects. Then OpenCV only has to find the bright spots in the image. All that is possible, though I cannot help you with that and also it is off-topic on this site.

If you can have a board with fixed positions, you could make direct electrical connections between the objects and the board. Though that means, that you would have metal contacts all over the board. I recently used such electrical connections to distinguish between different objects, which can be put into a small number of bays. I have 7 pins on each object, one of them ground. On the object I connected some of the other pins to the ground pin to create a binary pattern. The pins of each bay get read by a shift-in register. All registers are chained together and connected to the Arduino with a total of 4 pins.

Depending on your needs you could combine some of these options. I would try the OpenCV solution, or alternatively the reed switch with one RFID reader solution.

You should use the HC-SR0 ultrasonic sensor. It has good accuracy and range. If you don't want to use that, you can use an infrared distance sensor. If these don't work, please tell me why.


5V 10A 4 channel relay to 2 lights15W light in series in 220V AC supply I am trying to setup my first relay module with live environment. I have attached the relay module image below.

Which I am using to control 4 devices in my switch board as follows:

Fan (working fine),
6w celling LED panel (2 connected in series) (Working fine)
15w celling LED panel (2 connected in series) (Sometimes work sometimes don't)
Spotlights 3 lights in series and some LED strips connected to it (Sometimes works sometimes don't.).

I have cut one wire which is connected to main normal mechanical switch WHICH IS NOT A HOT WIRE its just the another wire connected to the button.

But I am not sure why its not working? Do I need to connect neutral to the another end of the relay. As I have only 2 wires connected to the relay for each of the switches. Here is a screenshot of specifications 15watt LED panel which is connected to my house, if this can help to understand better.

If I connect Neutral on the first pin of relay and when I close the relay switch, do the current will go into the neutral wire as well?

If I keep my 3w spotlights ON or more then 3-4 hours and try to close the relay on connected to it. The relay LED light for that connected relay goes OFF but the light don't. Seems like the mechanical relay is not getting enough power to move the mechanical relay off.

I want to know why this is happening? And how can I solve this issue? Attaching a neutral (earth) wire will help to reduce this? But if connect neutral to first (off side of relay) pin, then will get the current?

Any suggestions will be helpful. Also I added 3.3v from NodeMCU to VCC (instead of jumper) pin. But that is also not helpful.

You need to connect Vin from NodeMCU (Raw 5V from USB) to Vcc on the relay board.

And as stated in the comments, the relay need 5V for operating reliable.

In has the same problem, two LEDs and a resistor. To enhance it would be to replace the indicator LED (DS1-4) with a wire.

2 x LEDS á ~1.8V and a resistor á ~1.4V = 5 Volt.

1 x LED á ~1.8V and a resistor á ~1.4V = 3.2 Volt.


SoftwareSerial Struggles Just trying to understand and use the SoftwareSerial

I want to connect a WiFi Module (ESP8266)
If I send an AT command to the module I would like to print a response on my pc screen in the serial monitor

Some example code it tried

   SoftwareSerial dbgSerial(10, 11); // RX, TX
   void setup()
   {
     // Open serial communications and wait for port to open:
     Serial.begin(57600);
     Serial.setTimeout(5000);
     dbgSerial.begin(9600); //can't be faster than 19200 for softserial
     dbgSerial.println("ESP8266 Demo");
     //test if the module is ready
     Serial.println("AT+RST");
     delay(1000);
     if(Serial.find("ready"))
     {
       dbgSerial.println("Module is ready");

I would like to receive ready in the serial

Looks like you are swapping the use of Serial and dbgSerial. I think you mean to use Serial to print to the computer and dbgSerial to communicate with your module. Serial.println should display the message in the terminal on your computer.

while (dbgSerial.available()>0 ) {
   Serial.write(dbgSerial.read());
}


Help - Atmega328p, converting a PWM servo code from pin9 to pin6 I found a working code that uses pin9 (PB1) on my Arduino for controlling a Servo, but in my project, an ultrasonic sensor is already using that pin/timer. I want to convert the code to use pin6 (PD6), changed the registers according to the atmega's datasheet, but it doesn't work. Need help :/

The code should allow me to turn a servo using a potentiometer.

#define F_CPU 16000000 //16MHz
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdlib.h>

#define PWM_PRESCALLER 64
#define ICR_MAX (long double)F_CPU/PWM_PRESCALLER/50
#define OCR_MIN (float)ICR_MAX/37.5 // /8.75
#define OCR_MAX (float)ICR_MAX/8.7 // 37.5

volatile unsigned long adc_val=0;
volatile unsigned long counter=0;
unsigned long curr_adc=0;

ISR (ADC_vect)
{
adc_val += ADC;
counter++;
}

int main(void)
{
    DDRD |= (1<<DDD6);
    ICR1 = ICR_MAX;
    OCR0A = OCR_MIN;
    TCCR0A = (1 << COM1A1) | (1<<WGM00) | (1<<WGM01);
    TCCR0B = (1<<WGM02) | (1<<CS01) | (1<<CS00);
    ADMUX = (1 << REFS0);
    ADCSRA = (1 << ADEN)|(1 << ADATE)|(1 << ADIE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);

    sei();
    ADCSRA |= (1<<ADSC);

    while(1)
    {
        if(counter >= 1000)
        {
            cli();
            unsigned long round_val = round(adc_val / counter);
            adc_val=0;
            counter=0;
            if(abs(round_val - curr_adc) > 1)
            {
                curr_adc = round_val;
            }
            long double ocr = OCR_MIN + ((long double)curr_adc * (OCR_MAX - OCR_MIN)/1024);

            OCR0A = (int)round(ocr);
            sei();
        }
    }
}

PORTB bit 6 is controlled with TIMER0 while PORTB bit 1 is controlled with TIMER1.  Therefore you need to change the timer variables appropriately.  One mistake in your code is that you leave ICR1.  It should be OCRA if you want to use TIMER0.

I agree with Nick Gammon's comment that it is a lot easier using the Arduino Platform and use AnalogRead() function in conjunction with the servo library.

Having said that, you have chosen to write the program from scratch as many others prefer to do for one reason or another. I wanted to pass on the 2 web pages that I always go to when I am playing with the PWM frequencies and setup.

http://playground.arduino.cc/Main/TimerPWMCheatsheet
https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM


Error in my Arduino code " error: expected unqualified-id before ‘if’ " I cant seem to find this error is:

elevator_bug_2.ino:38:1: error: expected unqualified-id before ‘if’

Here is the code:

// these constants won't change. They are the
// lowest and highest readings you get from your sensor:
const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 600;    // sensor maximum, discovered through experiment

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the sensor:
  int sensorReading = analogRead(A0);
  // map the sensor range to a range of four options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

  // do something different depending on the
  // range value:
  switch (range) {
    case 0:    // your hand is on the sensor
      Serial.println("dark");
      break;
    case 1:    // your hand is close to the sensor
      Serial.println("dim");
      break;
    case 2:    // your hand is a few inches from the sensor
      Serial.println("medium");
      break;
    case 3:    // your hand is nowhere near the sensor
      Serial.println("bright");
      break;
  }
  delay(1);        // delay in between reads for stability
}

if (Serial.println("dark") == true)   // LINE 38
{

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}
}

C is procedural language and code is compiled. You cannot put code beyond procedure as you try to do in mentioned if. Remaining code following this point is nonsense. Do you mean you can put second loop() based on if condition ? I recommend to start learning programming C before using Arduino. In C you can do such a idea using preprocessor directives IF, ELSE, ENDIF.

I'm no expert but when asking "if" I want you to do this.
There should be an "else" I want you to do this.

For example:
I ask you if the door is open, then close it.
But what if the door is already closed, what do you do now?
That's why an "if" needs an "else".

"If" the door is open, then close it.
"Else" do nothing.


Burn bootloader to Arduino Uno using ARM-USB-OCD I have ARM-USB-OCD created by OLIMEX. I am interested in can I use this to burn a bootloader to Arduino Uno. As I know Atmega 328P can be programmed using JTAG protocol which has also ARM-USB-ODC, so if it really can anyone give the circuit or something like this.
Here is my device (ARM-USB-ODC) manual.

Probably, but likely not easily

To program an AVR chip you likely want to use the AVR ISP protocol, which is not JTAG, but like JTAG is a synchronous serial protocol with a clock, a data line in each direction, and one additional control pin compared to the several mode/status pins of JTAG.

According to your link, the ARM-USB-OCD is based on an FT2232C USB interface chip.

avrdude documentation indicates that this is an interface it knows how to use, though it will likely take some study to figure out how.

The final question would be wiring - you'll need to figure out which JTAG-style signal names map to which FTDI functional pins, and how those should best be connected to AVR ISP pins in a way which avrdude can use.  Additionally, you'd have to make sure that any buffering between the FTDI chip and the pins is compatible with your needs, both in terms of data direction and voltage level.

Note that you can easily use any ATmega328-based Arduino as an ISP programmer for a same-voltage target - not really production worthy, but if you just need to move your project along today it's a handy option.

I offer a '328P based programmer that downloads code from SD card into the target over the ICSP pins (SCK, MOSI, MISO, Reset, power, Gnd). There are details on it here http://www.crossroadsfencing.com/BobuinoRev17/Programmer.html

Nick Gammon developed the code, and tweaked it some for me for a fully standalone programmer with status lights, display, and a rotary encoder for file selection, up to 256 files supported.

http://www.crossroadsfencing.com/BobuinoRev17/Rev7Battery_with_Arduino.jpg


Process Sensor Data from Arduino Yun with Python I'm currently working on a small project with my Arduino Yún.
I want to process the sensor data in python and send them in a message queue. I need to use Python3.

I cannot find a way to get the sensor data in my Python code.
I already tried to start the python process in my sketch and use the println method of the process object but this doesn't work.

I also tried to use the BridgeClient class from the Arduino Github but it won't work either.

Summarized:
I can't find a way to send my measurements from my Arduino sketch to the my Python3 program on the Linux side of the Arudino Yún.

I don't think this is an extraordinary problem and I don't understand why there aren't any tutorials for this specific use-case.

The section below contains my Arduino sketch, which does the measurements.

#include <SparkFunHTU21D.h>
#include <Wire.h>

HTU21D myHumidity;

int trigPin = 11;
int echoPin = 12;

void setup() {
  // put your setup code here, to run once:
  pinMode(A1, INPUT);
  Serial.begin(9600);

  myHumidity.begin();

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  //Perform 5 SoilMoisture-measurements and get mean
  float soil = meanSoilMoisture(A0, 5);
  float humd = myHumidity.readHumidity();
  float temp = myHumidity.readTemperature();

  float distance = getDistance();

  String dataString;
  dataString += String(soil) + ", " + String(humd) + ", " + String(temp) + ", " + String(distance);
  Serial.println(dataString);

  delay(4000);
}

long getDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  long duration = pulseIn(echoPin, HIGH);

  // Convert the time into a distance
  return (duration/2) / 29.1;     // Divide by 29.1 or multiply by 0.0343
}

float meanSoilMoisture(int analogPin, int nMeasurements) {
  float sum = 0;
  for(int i = 0; i < nMeasurements; i ++) {
    sum = sum + readVH400(analogPin);
    delay(50);
  }

  return sum / nMeasurements;
}

//Perform Measurement
float readVH400(int analogPin) {
  int sensor1DN = analogRead(analogPin);
  float sensorVoltage = sensor1DN*(3.0 / 1023.0);
  float VWC;

  // Calculate VWC
  if(sensorVoltage <= 1.1) {
    VWC = 10*sensorVoltage-1;
  } else if(sensorVoltage > 1.1 && sensorVoltage <= 1.3) {
    VWC = 25*sensorVoltage-17.5;
  } else if(sensorVoltage > 1.3 && sensorVoltage <= 1.82) {
    VWC = 48.08*sensorVoltage-47.5;
  } else if(sensorVoltage > 1.82) {
    VWC = 26.32*sensorVoltage-7.89;
  }
  return(VWC);

}

I'd like to have a way to send dataString to the linux side of the Arduino Yún and process it with Python3.

As explained earlier I've already tried out multiple solutions, e.g. start a new process and use the println method of the process.

{...}
Process proc;
void setup() {
    {...}
    proc.begin("python3 /mnt/sda1/test.py");
    p.runAsynchronously();
    {...}
}
{...}
    proc.println(dataString);
{...}

I've tried to read this dataString in Python3 in different ways, e.g. I've used the input method, because I read in a forum that I can handle such input like a keyboard input.
It didn't work and I didn't get an error, neither in Python nor in my sketch.

I've read different examples using the Bridge library. So I set up the sketch:

{...}
bridge.put("data", dataString);
{...}

I'd like to try out the BridgeClienton the python side but this library was written in Python2. I don't want to migrate the library to Python3 and I need to use Python3, so I didn't find a way to write Python code here.

I would highly appreciate any help from you.

You might want to try the Process method, although, looking at your recent edits to the question, it seems like you already have.

Nevertheless, I was having difficulty getting my head around the problem when I first used my Yún, and I found the information below helped me understand how to get up and running. You do say that you've tried many solutions already, and maybe you've already seen this, but as you don't list which solutions you have already tried (apart from one), I thought it might be worth posting this link as an answer.

From this post to the thread on the Arduino forums, Yun Serial connection between Arduino and Linux

  Accepting HTTP connections, as shown in the Bridge tutorial, is
  but one facet of the Bridge library. (And probably the least useful
  and least efficient facet.) It is intended for accepting incoming
  connections from the greater network, not necessarily the local Linux
  processor.

  The Bridge library is a collection of different classes that perform a
  variety of operations, all over the serial link between the two
  processors, and all can be used at the same time. The Bridge uses a
  network port paradigm, not HTTP. Using ports gives it a little more
  overhead, but it allows multiple simultaneous "connections" between
  the sketch and Linux sides.

  I suggest you take a look at the Process tutorial. It does what
  you want, and 95% of the time it is the only part of the Bridge
  library that I use. The example defines Process objects that are local
  to a function, which run simple commands that do a little bit
  different f processing, return a result, and then exit.

  My projects typically define a global Process object which starts a
  Python script, and keeps the connection open. Once open, the sketch
  can write to the Process object at any time, and the Python script
  reads that data from STDIN. Python can write to STDOUT at any time,
  and the sketch can read it from the Process object. The Process class
  derives from the Stream class, just like Serial, so your sketch can
  use any of the read/write methods you would use for a serial port. On
  the Linux side, you are just reading/writing as you would to the
  console. By default, Pythons runs in a buffered mode: I've found that
  you need to add the -u option to the command line that runs your
  Python script, or add it to the hashbang at the beginning of your
  script.

  There are those who disable the Bridge library, and use the serial
  port manually on both sides. This can be done, but I've not had to
  resort to that yet. The Process class does everything that a direct
  serial connection can do, and more: you can have multiple simultaneous
  Process connections going, and you can still use all of the other
  Bridge library features. If you disable the Bridge library, you get
  just the one connection stream. It would be a bit more efficient, but
  unless you are dealing with high amounts of data, I'll bet you don't
  need to do that.

  My typical project has the sketch running as a rather dumb I/O
  processor, passing barely digested input data down though one or more
  Process objects to a Python script. The Linux side does all of the
  heavy processing and network communications, and then sends output
  data back up the sketch which outputs it to the pins.


Can I use arduino's 3.3 V output directly to esp8266? I just bought esp8266 and ftdi usb driver, I want to power the esp8266 with Arduino's 3.3 V output, is that possible?

I saw some tutorial on youtube in that they are suggesting us to use 3.3v regulator ic instead of directly power 3.3 V of Arduino or ftdi driver's 3.3 V output.

If I connect my ftdi or Arduino output directly into esp8266 is there a chance to damage the esp8266?

You should search for this data yourself, but since you are saying you are a newbie I'll tell you how to find this.

First of all you should search for a document called "datasheet". On a datasheet the producer writes all the relevant data about his product.

In your case, you should search for the electrical characteristics of the ESP8266. For instance here you have one of the datasheets. On page 13, there is the "Power consumption" chart, which says that the worst case has a typical current of 170mA. I suggest you to raise it a bit; let's say you need 250mA for the ESP.

Now, the arduino. You should search for the schematic of the board or read the part number of the 3.3V regulator. Since it's easier from the schematic and they released it on the web, you can see that the part number of the 3.3V regulator is LP2985. Searching for it on google will lead you to the texas instruments webpage, with the datasheet. Here you can see that the maximum output current is 150mA, so below the required current. Answer: you can't with arduino.

As for the FT232 cable, you should search for it because there are different models. Search on google and pick the first link pointing to the ftdi website.

As an example, the TTL-232RG has this datasheet. On page 9 they say that the TTL-232RG-VSW3V3-WE has an output current of 50mA, so you can't use it. The TTL-232RG-VREG3V3-WE, on the other side, has a maximum output current of 250mA, so you can use it.

If you have further questions, just ask here ;)

i know It's a delayed reply .but it might help some one else.The answer is yes. I powered up esp8266 with ardino 3.3V directly and it works fine for me.


How to Store the Value of A Sr04 Ultrasonic distance sensor (ping)? I am using a Sr04 Ultrasonic distance sensor with Uno clone for making a Alarm. The basic idea behind this project is that In Setup, Read the distance And store it in a varibale as Threshold. And in Loop, Check the distance readings regularly and if the Reading anytime is not equal to The threshold (that means someone interrupted in front of ultrasonic sensor), then a led flashes. I Know that is system is not enough good because the real world is a bit noisy. My problem is I am storing the theshold distance in "int" variable. The compiling error is "Cant convert Long Unsigned char to Int" something like this. Please tell me how can I store the reading of my sr04 sensor in a variable. I am using NewPing Library.

First you must verify that storing the value as int is even possible: long int can represent much larger values than int. Are you 100% sure that the maximum reading you will ever get can be represented as int?
In case the answer to the previous question is "yes", then you can just cast it on the fly:
int int_val = (int)function_returning_longint();
In case the answer is "no", you can either give up the idea of using int and stick with long, which is not necessarily bad, or you can scale down the value, at the price of loosing some resolution:
int int_val = function_returning_longint() >> 8; This assumes that long is 16 bit and int is 8 bit, but it would be preferable to use explicit types, like int8_t and int16_t. And in your case you might have to shift by a different value than 8.

Either way, do not make casts of from big type to small type without being 100% sure that the max value you will ever deal with can fit in the small type.

If you want to store it as int, you have to firstly store it in a long type then convert it into int.

For instance:

long i;
int j;
i = getReading();
j = (int) i;

There are many ways to do it, for example you can also use rounding to convert it into integer variable.


How to set cables to connect Cp2102 to Pro Mini? How to connect the cables in order to program the pro mini with the CP2102 usb interface ?
The TX RX and GND is easy, but I am not sure about the RST, DTR, DST, etc
I attached the images of both.

EDIT: When I try cables like this:

TX  ... RX
RX  ... TX
5V  ... VCC // my pro mini is 5V version
GND ... GND
RST ... RST

The board lits up and green starts blinking, this should be the default blinker program.
I click upload, I get this error, and I assume the cables are not properly connected:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x89
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x89

I know some people mentioned it works by adding some resistor and capacitor, but I was hoping that is an error and it should work without that complication.

RST to RST. Ignore the others, they are irrelevant.

Pretty sure RST is Reset input to the CP2102, that will not work.

DTR to DTR (BLK on the Promini) will work, the DTR Low level goes thru the Promini's 0.1uF cap and 10K Reset pullup resistor to make a Reset pulse. That's how the FTDI Basic works when connected.

RTS (Request To Send output) might also work, that is supposedly a pulsed level.


Difference between these two relays (D1 Mini Relay Shield and Single 5V Relay) I've setup my NodeMCU v3 with this relay and I got this:

When using 3V to power the relay, I can hear coil when I turn on the board and I can only turn it on once. Then I can no longer hear the coil, but LED turns on and off.
When using VU pin (5V) to power the relay, I get the same coil sounds (when turning on board and on first toggle), then nothing. But the LED stays on, just slightly dims itself when turning on. Barely noticeable.

Alright, but I had a D1 Mini relay shield* laying around and I decided to give it a try. And it worked when powering the shield with VU pin (5V).

So my question is what is the difference? Does the D1 Mini Relay Shield have a transistor to pull up pin voltage from 3V to 5V and the other relay doesn't? If I had a logic level converter 3V-5V between the NodeMCU GPIO and the relay IN, would it work?

Thanks in advance.

*must say mine is a clone, but it works

Ok, so:

I've bought a logic level converter.
Bought another relay.

Now to the results:

With the first relay, no joy with 5v or 3v in any combination (3v on VCC / 3v on IN; 5v VCC / 5V IN; 3V VCC / 5V IN; 5v VCC / 3V IN)
With the second relay (the new one), funny enough.. Didn't work with 5V on VCC and 5V on input. But it did work with 3v on both of them.

I measured every output voltage to make sure everything was working fine and it wasn't a problem with power supply.

I guess it should work with 5v...? Right?

Anyway, it was indeed a faulty relay. And 3V on VCC and Input is what worked for me, even though it is a 5V relay. Thank you all for the assistance.

More than likely it is a faulty board.

The schematic for the D1 Mini relay shield can be found here.

I couldn't find a schematic for the relay that is having the problems but you can see from the picture below that it has 2 LEDs (power and relay signal), a flyback diode and a FET or transistor.

As you can see the circuits are pretty much the same. So my conclusion is that you have a faulty relay board.


Interconnected Arduinos via digital pins and magnets Before i get too far into the design phase of a project i have in mind, is there a way to connect arduinos in a non-master/slave manner to pass a few different combinations of HIGH/LOW (say 5) or 'information' both ways using digital pins? Perhaps some library i don't know about?

Each of these modules should be identical and be able to connect on any face to any other module. I've included a crude image of what I would like to accomplish.

I've already determined that i can solder to these neodymium magnets without loss of magnetic properties by having the little magnets attached to a stronger magnet during the soldering process. Magnet to magnet connection shows only a very tiny resistance.

If it can't be accomplished, i will need to abandon the project and look for some other means to make my project. Thanks in advance!

~zen

While idea looks cool, you need some kind of "locks" because not "any combination" can work.

Rotate second Arduino in bottom row on 180 degree and you will see that GND/5V reversed relatively to first arduino in second row.

You have to account magnet N-S polarities to allow good lock. Probably you can use magnet polarities to achieve proper orientation.

Non-master/Slave is absolutely the best for lots of applications.
Why bother with Arduinos? There are much better processors available at low cost.
Lots of the STM32 processors allow you to address the serial ports.
For instance, from the reference manual of the popular STM32F103 (Blue pill).Quote.
Address mark detection (WAKE=1)
In this mode, bytes are recognized as addresses if their MSB is a ‘1’ else they are
considered as data. In an address byte, the address of the targeted receiver is put on the 4
LSB. This 4-bit word is compared by the receiver with its own address which is programmed
in the ADD bits in the USART_CR2 register.
The USART enters mute mode when an address character is received which does not
match its programmed address. In this case, the RWU bit is set by hardware. The RXNE
flag is not set for this address byte and no interrupt nor DMA request is issued as the
USART would have entered mute mode. Unquote.
Then use the Embitz compiler, free, use C or C++ if you have to.
C++ cannot compete with C for embedded work, proven over and over comparing code size and operating speed. Why use a processor without decent debugger?
Embitz and STM32 will give you an unbeatable debugger.
The larger STM32 processors also have Canbus, which is the ultimate non-master/slave.
Canbus is not difficult to set up, and you will never look back.
Alternatively, use ESP32 and Canbus.
Regards
Johan Smit


Is Arduino IDE enough to program with C or C++? I am using Arduino IDE to program my ATmegas with bootloaders. I can directly manipulate ports, use timers, interrupts, PWM pins and timers, etc. Everything is working.

But this question arises: Does the Arduino IDE differ from AVR Studio in terms of using C or C++ on an ATmega chip?

I know AVR Studio has some features or something. My question is not about that. My question is that I am coding everything, not using extra libraries, features etc.

In terms of the core language features, there's virtually no difference. In the background, the Arduino IDE and Atmel/AVR Studio both use GCC to compile the code.

GCC is an excellent toolset which supports all the core language features of C++. Admittedly, the version which currently comes with the Arduino IDE is a little old, so it doesn't support C++11 onwards. However, a lot of C++11 features are not very relevant or useful for microcontroller programming anyway (e.g. threading).

You're also likely to use the same standard library for both, which is AVR Libc. It provides pretty much all the standard C functionality that you're likely to use in an AVR project. It doesn't include the C++ stuff though, such as streams, containers, and algorithms. These tend to be very resource-hungry though, so are best avoided anyway.

The major difference is basically flexibility. Atmel/AVR Studio is designed to let you work on a wide range of projects and customize the build to suit very specific needs. You can also use alternative libraries with it more easily. In theory, the Arduino IDE can be modified in similar ways, but it's a major hassle because it provides no GUI to do it.

It's also important to note that the Arduino IDE does a number of non-standard things, such as re-organising declarations and including libraries in strange ways. It's designed to be more user-friendly, but often ends up just getting in the way. There are usually ways to work around those issues though.

It is unclear exactly what you are asking. The Arduino is different to most computers - it has NO OS (if you exclude the bootloader).

You can use a c/c++ compiler which translates your code to machine code. If you include libraries this may include machine code which someone else has compiled into a library.

You could write 100% of your code in assembler and produce exactly the same result.
Even in the good (bad?) old days of the 1970s before we had compilers on microprocessors it was common to have prewritten code (libraries) for common functions.

You haven't lived until you have written your own assembler (hand coded).


Is my TFT screen defective? I bought the standard 1.77" TFT screen months ago and It has never worked. I follow the wiring diagram shown for Uno on the guide on the Arduino website and the best result I have ever got is it seeming like the screen itself is broken. I must have rewired the whole thing many times now and quadruple checked each time.
As I have never used this screen before I do not know what is correct any further than the tutorial.

I say that because it seems to understand instructions but does not display them correctly.
I have tried multiple examples and tests on it that all yield weird results.
The tests I have tried are:

The SD demo that loads the Arduino icon off SD and fills the screen
with it. The serial connection says that it has successfully read the
image but just displays black lines
Setting the background colour with random colours which seems to work fine apart from the black bars
Drawing random colour, positioned and sized rectangles. Result is image below. Colours seems to prefer pink, purple and white.

As you can see it looks like the image is 1D, no rectangles stop across the x axis so I did a test for that, it just draws a 1x1 pixel red dot going down the screen's left side, if it drew a red line moving down then my thought that it was stretching the first column would be correct, it didn't, just white and black bars still, so I modified it to test every column in case it wasn't column 0, same result...weirdly only when I made the 1x1px rectangle 5x5 my idea was correct.

As you can see on both the images, the black bars are a persistent factor, their colour cannot be changed and they appear once TFT.begin has been called.

After looking around the only help I could find is someone mentioned that Arduino the company updated the TFT library but not the software but he/she didn't provide a download link. In the time I've had this I'm sure I'm redownloaded/updated the Arduino software a few times too.

Are the glitches normal for wrong pin connections? Is there some pin wrong on the website?

It's pretty hard to see the wiring for sure in the photo, but you have an extra red wire looped from one side to the other, what is that for? It's not in the tutorial. Other than that, your wiring looks ok to me, as far as I can see from the photo. So probably it's broken, I hope you can return it.


Human circuit trigger The main idea is to create trigger which can be switched on by touching 2 plates on opposite walls. And these should be performed by few peoples holding each other hands.

Obviously human body has big resistance so I couldn't just connect these plates to ground and to one of Arduino pins.

There is a toy that do almost what I what (see it there). But I haven't found any information about how to create it by myself.
Do you have any ideas how to create it?

I just tried it (using my own method), and I got it working with very good sensitivity (should be fine for two people) using a TIP102 Darlington transistor and some resistors. Here is what I did:

R1, the 1M pulldown resistor on the first pin of the Darlington is necessary to keep the light off when nobody is touching the wires. Without this, the light will turn on and off frantically.

R2, the 1k resistor keeps the Arduino from draining too much current (since that would be bad for the pin) in the case that your A0 is in OUTPUT mode and set to LOW.

R3 keeps the LED (or in my case, an AC relay connected to an actual light) from draining too much current from the Arduino. Note: The LED leads may be backward (reverse polarity) in the provided diagram.

Here is the code:

// I release this code under the standard MIT licence;
// (in addition to whatever StackExchange implies);

const short triggerThreshold = 10;// Lower is more sensitive;

void setup() {
  pinMode(A0, INPUT);
  pinMode(A5, OUTPUT);
  digitalWrite(A5, LOW);
  delay(1);
}

void loop() {
  short value = analogRead(A0);
  digitalWrite(A5, (value > triggerThreshold) ? HIGH : LOW);
  delayMicroseconds(10000);// 10ms;
}

Note the triggerThreshold setting in the code. If you want more sensitivity, try changing the 10 to a 5. I just tried it, and it becomes extremely sensitive, yet it still appears to reliably stay off when I don't touch it. Naturally if you use large plates for touching, electrostatic in the air could set it off, so you may need to change this number to be higher to make it less sensitive, depending on your setup.

You can do it with an Arduino !
Use any of the ADC pins
There will be change in the ADC i/p when there is some resistance b/w the pins !
Try both
+ve > (people) > ADC
-ve > (people) > ADC
Just do some trials and probably will notice the change in ADC pin outputs .
If you want to make  it more sensitive
Add a high resistance to the ADC pin
if you are giving +ve to touch plates add a resistance from ground to that ADC pin


Question: how to join two different codes I’m dabbling in Arduino and having trouble running two sketches on my Arduino UNO simultaneously. The first is about a program that reads temperature and relative humidity and the second is a program that reads barometric pressure. Both programs work independently, but when I try to combine the two, No
help
this is the code for temperature and relative humidity:

#include <Adafruit_Sensor.h>
#include <LiquidCrystal.h>
#include <DHT.h>
#include <DHT_U.h>

//VARIABLES
//Asignación de los pines digitales
int SENSOR = 2; //Este es el pin #2
int RS = 4;
int E = 5;
int D4 = 6;
int D5 = 7;
int D6 = 8;
int D7 = 9;
//Variables de lectura de tempratura y humedad
int temp;
int hume;
//Creación de variables para el sensor y el display
DHT dht(SENSOR,DHT11);                    //Formato general: DHT <var_name>(PIN, MODELO DEL SENSOR)
LiquidCrystal lcd(RS, E, D4, D5, D6, D7); // Formato general: LiquidCrystal <var_name>(RS, RW, ENABLE, D0, D1, D2, D3, D4, D5, D6, D7)
//Variable para salida del abanico
int motor = 12;

void setup(){

  //Iniciar el sensor de temp
  dht.begin();
  //Iniciar el LCD
  lcd.begin(16,2); //(tipo 16 columnas, 2 líneas)
  //Setea el Pin 12 como salida
  pinMode(motor,OUTPUT);

}

void loop(){ //Este es el buclé principal del programa

  //Lee valores físicos
  hume = dht.readHumidity();
  temp = dht.readTemperature();

  //Limpia el LCD
  lcd.clear(); //esta instrucción coloca el cursor en la pos 0,0 (columna, fila)
  lcd.setCursor(0,0); //(no necesaria porque la linea de arriba ya lo hace)
  //Escribe los valores leídos en el LCD
  lcd.print("TEMPERATURA: ");
  lcd.print(temp);
  lcd.print("C");
  lcd.setCursor(0,1); //esta instrucción coloca el cursor en la pos 0,1 (columna, fila)
  lcd.print("HUMEDAD: ");
  lcd.print(hume);
  lcd.print("%");

  //Activa el motor si la temperatura pasa el valor deseado
  if(temp>=30){ // Compara si la temp ya es 30 grados
    digitalWrite(motor,HIGH); //Si lo es manda un 1 lógico a teavés del pin digital #12
  }
  else{
    digitalWrite(motor,LOW);// sino, manda un 0, lo que apagaría el motor
  }

  delay(2000);//valor en milisengundos para que repita el ciclo

}

and this is the barometric pressure code:
#include <Wire.h>
#include <Adafruit_BMP085.h>

// Connect VCC of the BMP085 sensor to 3.3V (NOT 5.0V!)
// Connect GND to Ground
// Connect SCL to i2c clock - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 5
// Connect SDA to i2c data - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 4
// EOC is not used, it signifies an end of conversion
// XCLR is a reset pin, also not used here

Adafruit_BMP085 bmp;

void setup() {
  Serial.begin(9600);
  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
}

void loop() {
    Serial.print("Temperature = ");
    Serial.print(bmp.readTemperature());
    Serial.println(" *C");

    Serial.print("Pressure = ");
    Serial.print(bmp.readPressure());
    Serial.println(" Pa");

    // Calculate altitude assuming 'standard' barometric
    // pressure of 1013.25 millibar = 101325 Pascal
    Serial.print("Altitude = ");
    Serial.print(bmp.readAltitude());
    Serial.println(" meters");

    Serial.print("Pressure at sealevel (calculated) = ");
    Serial.print(bmp.readSealevelPressure());
    Serial.println(" Pa");

  // you can get a more precise measurement of altitude
  // if you know the current sea level pressure which will
  // vary with weather and such. If it is 1015 millibars
  // that is equal to 101500 Pascals.
    Serial.print("Real altitude = ");
    Serial.print(bmp.readAltitude(101500));
    Serial.println(" meters");

    Serial.println();
    delay(500);
}

You need to write one program using elements from each block of code. There is no way the Arduino will run both programs concurrently, it will only run one or the other.  You can copy and paste them together but unless done correctly it will not work. This is why it is important to understand the code you are using.


Why can't the Atmel ATtiny family delay over a minute? I have some really simple code and tested on an 8 MHz ATtiny85 and ATtiny2313. It's basically a blocking blink:

int relayPin = 7;

long offPeriod = 1 * 60 * 1000;
long onPeriod = 1 * 60 * 1000;

void setup()
{
  pinMode(relayPin, OUTPUT);
}

void loop()
{
  digitalWrite(relayPin, LOW);
  delay(onPeriod);
  digitalWrite(relayPin, HIGH);
  delay(offPeriod);
}

When I assign onPeriod and offPeriod to be 1 * 1000 (1 second), the LED will blink as expected. When I add the 60 second multiplier in, it seems to fail.

For the ATtiny85 I use Arduino Pin 4 (physical pin 3) and for the ATtiny2313, I use Arduino pin 7 (physical pin 9).

I program through the Arduino IDE using boards manager to install the ATTinyCore library for the ATtiny2313 and this for the ATtiny85.

Am I doing something wrong here?

It looks like if I throw the delay in a function, and then invoke it with however many seconds I want, it will work. This is not good as it remains blocking. So perhaps the correct way to do this is to grab timestamps.
Here's the somewhat working code:

int relayPin = 4;
unsigned long offPeriod = 60;
unsigned long onPeriod = 60;

void setup()
{
  pinMode(relayPin, OUTPUT);
}

void loop()
{
  digitalWrite(relayPin, LOW);
  delaySeconds(onPeriod);
  digitalWrite(relayPin, HIGH);
  delaySeconds(offPeriod);
}

void delaySeconds(int s) {
  for (int i = 0; i < s; i++) {
    delay(1000);
  }
}

This is absolutely nothing to do with "why can't the atmel attiny family delay over a minute?". It is all to do with the way that C++ works.

See my page about Integer arithmetic and overflow.

To excerpt from that:

On the Arduino (Uno) platform, what do you think will be printed here?

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  Serial.println (30000 + 30000); // twice 30000
  Serial.println (60 * 60 * 24);  // seconds in a day
  Serial.println (50 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

Did you guess:

60000
86400
500

Nope!

It prints:

-5536
20864
0

This is because of integer arithmetic. If the compiler can, it treats an numeric literal (like 60) as an int type, which means it has the range -32768 to +32767.

And, arithmetic is done using the type of the largest argument, which means the arithmetic in each case is done as 16-bit arithmetic, and thus it overflows once it reaches 32767.

For example, 30000 + 30000 = 60000 which is 0xEA60 in hex. Unfortunately, 0xEA60 is exactly how -5536 is stored in an int type, which is why it prints -5536.

Meanwhile, 60 * 60 * 24 = 86400 which is 0x15180 in hex. As that doesn't fit in 16 bits, it is truncated to 0x5180 which is 20864 in decimal (as printed).

Finally, in integer arithmetic 50/100 is zero, multiply zero by 1000 and you still get zero, which is why the final result is zero.

Solution

First, you can add a suffix to numeric literals (eg. L for long, or UL for unsigned long), and add a decimal place to floats, like this:

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  Serial.println (30000L + 30000); // twice 30000
  Serial.println (60L * 60 * 24);  // seconds in a day
  Serial.println (50.0 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

Now we get:

60000
86400
500.00

You only need to help out with the first literal, once the compiler knows we are using longs (or floats) it sticks with them for the expression.*

* It's actually somewhat more complex than that as this link explains: Understand integer conversion rules.

The compiler "promotes" a value in an expression to match another "higher-ranked" type, under certain circumstances. For example, adding an int and a long will result in the int being promoted to a long (regardless of whether it appears first in the expression or not). However if an int is being added to another int, it will not promote them to a long, even though the result may not fit into an int.

According to AVR libC the implementation of the delay function has a limited value range that varies with the F_CPU macro definition. So your delaySeconds(int) function is the only solution.


programming arduino in pure c I'm trying to flash pure c-code to arduino Mega2560 board from linux using avr-gcc & avrdude. Compilation is done , now trying to flash using avr-dude, getting error as "avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00"

I used below command to produce hex file

avr-gcc -mmcu=atmega2560 -DF_CPU=16000000UL led.c -o led.elf

In file included from led.c:3:0:
/usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler optimizations disabled; functions from  won't work as designed" [-Wcpp]
 # warning "Compiler optimizations disabled; functions from  won't work as designed"

And then

avr-objcopy -j .text -O ihex led.elf led.hex

finally for flashing

avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex

FYI: port is correct & RX pin is blinking i.e connection is perfect between computer & board

In file included from led.c:3:0:
  /usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler
  optimizations disabled; functions from won't work as designed"

You should start by fixing this. Simply add -Os to the compiler
command line. This means “optimize for size”, and is the standard
optimization option used with Arduinos.

  avr-objcopy -j .text -O ihex led.elf led.hex

If your copy of avrdude was compiled with libelf (like the one supplied
with Ubuntu is), you don't need this: you can hand your elf file
directly to avrdude.

  avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex

-F tells avrdude to not verify the device signature. -V tells it
to not verify the upload. I wouldn't use any of these options unless
I had a very good reason to do so. -c arduino is wrong: it selects the
upload protocol used by optiboot (used, e.g., in the Uno). The
Mega 2560 uses a different bootloader based on the “wiring”
protocol. I would also add the -D option (disable auto erase) because
I saw the Arduino IDE using it, and because without this option I get
the error:

avrdude: erasing chip
avrdude: stk500v2_command(): command failed

In the end, the upload command ends up being something like:

avrdude -p atmega2560 -c wiring -P /dev/ttyACM3 -b 115200 -D -U led.elf

I'm trying to flash pure c-code

you cannot flash any C-code to any arduino, pure or not pure. the arduino only takes binary code.

with that said, the arduino compiler is capable of translating any pure C-code to binary, to the extent that you can write pure C-code.

So once you have an arduino toolchain, you basically have had all necessary tools to write pure C-code.


Bluetooth connection to HC-05 paired but not connected (in Linux) I have an Arduino Uno connected to an HC-05 Bluetooth sender/receiver chip. I am trying to create a Bluetooth connection between my Acer laptop running under Ubuntu 14.04 LTS and the HC-05 chip.

Ubuntu detects the HC-05 chip, as can be seen below.

phodor@ubuntu: hcitool scan
Scanning ...
    11:22:33:44:55:66   HC-05

I am able to create a pair between my laptop Bluetooth device and the HC-05 chip. However, I am unable to create a connection with that pair from the Ubuntu interface. The "Connection" button cannot be clicked on, as you can see on the figure below.

I tried creating a connection using the terminal, but after that the terminal still did not detect any connection.

phodor@ubuntu: sudo hcitool cc 11:22:33:44:55:66
[sudo] password for phodor:
phodor@ubuntu: hcitool con
Connections:

I also checked that my computer Bluetooth device was working.

phodor@ubuntu: hcitool dev
Devices:
    hci0    AA:BB:CC:DD:EE:FF

Any idea why the connection cannot be created ? Any idea on how to do it using the Ubuntu interface or the terminal ?

you can try this website for more information

http://wiki.micropython.org/official-accessories/Bluetooth-module-HC05


Why does current flow along a wire instead of a resistor right next to it? I am having trouble understanding exactly what is going on in a circuit where when a button is pressed an LED goes on. Also, I have the Arduino UNO.

The schematic can be seen at:

2:36 of this video: Arduino Tutorials: Control a LED with a Button.

So, the part that I don’t understand is, how come when the button is clicked and the current can pass through, the current doesn’t go through the pull down resistor and instead goes along the input wire?

I’m a beginner but do understand concepts like voltage, amps, resistors, Ohm’s law, etc. So answers don’t have to be super simple, but simple enough that I can understand them. Thanks!

So, the part that I don’t understand is, how come when the button is clicked and the current can pass through, the current doesn’t go through the pull down resistor and instead goes along the input wire?

Simple: It does go through the pull down resistor. But  it also goes down the "input" wire.

For simplicity you can imagine that the input is simply a very large resistor. Say, 1MΩ.

The circuit can then be simplified as:

simulate this circuit – Schematic created using CircuitLab

Contrary to popular belief, current does not take the path of least resistance. It takes all possible paths. The quantity of current through each path is proportional to the resistance of the paths.

In this example we have two paths - one with 10kΩ and one with 1MΩ.  That's a ratio of 1:100, and the current will be split accordingly.

You can calculate the current that flows through each resistor simple using Ohm's Law because the wires and switch are (in an ideal world) just not there. The 5V is directly connected across each of the resistors.

So for the 10kΩ resistor the current through is is:

     V      5
I = --- = ----- = 0.0005 = 500µA
     R    10000

And for the 1MΩ it is of course 100x smaller (I'll let you do the maths for that if you want to check), so 5µA.

The full current that the circuit takes is 505µA, with it split between the two resistors.

With the Arduino instead of the 1MΩ resistor it's exactly the same (though the current values may vary somewhat).  500µA flows through the 10kΩ resistor, and "some tiny current" flows through the Arduino.

However, with all that said, the Arduino really doesn't care about the current. All it cares about is the voltage. With the button pressed both the input and the 10kΩ resistor are connected directly to the 5V supply - so the Arduino reads that as "HIGH". When you release the button the input is now connected to ground through the 10kΩ resistor, but there's no current to flow, so there's no voltage across the resistor (the voltage across a resistor is proportional to the current flowing through the resistor - Ohm's Law), so it's as if the input is connected directly to ground - and the Arduino reads that as "LOW".

To be more technically accurate the input of the Arduino is actually more akin to a tiny capacitor.  When you apply 5V to the input it charges that capacitor up. Once it reaches 60% of 5V the Arduino recognises it as a "HIGH" signal.

When you release the button that capacitor is then connected to ground through the resistor, and it discharges through that resistor. Once it drops to 30% of 5V the Arduino sees it as being "LOW".

If you don't have the pull-down resistor, when you remove the 5V from the input that capacitor is still charged. So the Arduino still sees it as a HIGH. The charge in the capacitor will slowly bleed away until it's low enough to be seen as low.

But, (and it's a big but), the capacitor is very sensitive and can be charged up again by ambient energy around the place (radio waves, static electricity, etc). It can harvest enough energy from the environment to get back up to the 60% of 5V and be seen as "HIGH" again. This is known as "Floating", and is something you do not want in your circuit. The input "flaps around" between HIGH and LOW with no control.  Which is why the pull-down resistor is absolutely essential.

the answer is within the question,
Electrons will quite happily travel along a wire until they hit resistence as in a resistor.
where there is less resistence too flow that is the path they will take.
The path of least resistence you might say.


arduino ethernet shield I bought a ethernet shield for my Arduino Uno. I plug it my Arduino and PC with ethernet cable. There is all led is working on ethernet shield. But when i try to examples about ethernet which is in Arduino IDE as "DHCPChatServer" example.

I hope to see;
"Trying to get an IP address using DHCP"
"My IP address: 192.168.1.177"

But I just see "Trying to get an IP address using DHCP"

Any problem with my ethernet shield?

When you connect your arduino directly to the PC using the ethernet cable, neither of them have any information about the network.

Most ethernet devices attach to switches, routers, and gateways, and one or more of these devices host network services such as DHCP, DNS, or provide a way to obtain those services.

Without DHCP, for instance, neither your PC nor the Arduino know what IP adress to use, what their netmask is, and whether there's a gateway to other IP addresses.

You have a few options:

Follow the Automatic Private IP Addressing specification, which windows computers default to when no DHCP server is present or available. Set the IP address of the Arduino to 169.254.x.y where x and y are randomly chosen numbers between 0 and 255, and set th netmask to 255.255.0.0.  The windows computer should have done the same if no static IP address was set - use ipconfig on the windows command prompt to find its IP address.  Your computer and arduino should be able to talk to each other.
Set up a router. It doesn't need to connect to the internet, it just needs to connect to both the PC and the Arduino.  It'll implement a DHCP server and make sure, at minimum, that the two devices can talk to each other and the router.
Set static IP addresses on both devices.  Set up the PC with something like 192.168.42.1 with a netmask of 255.255.0.0 and the Arduino with 192.168.42.2 and the same netmask.  Now they should be able to talk to each other.
Connect both to an existing network.  The network should already have a router with DHCP on it, so it'll take care of everything, and as a bonus you may be able to get internet access as well, which could help with testing since you can use the ethernet shield to communicate with google and other known working services, rather than trying to set up a server on the PC.

I changed my Arduino Uno with Arduino Mega and problem is solved.Thank you