Arduino stopped showing up in /dev and dmesg without response Arduino suddenly stopped being recognized.
It is not listed in /dev and
dmesg -w shows no activity at all when un/plugged.
I'm on Fedora 33. The Arduino is MKR-Zero. The cable is ok - other devices work well. I tried it on windows machine - same result - in Arduino IDE the option for port is greyed out.
Very weird thing happened before this issue- when I was trying to flash sketch, audio connected to docking station switched to speakers in laptop and keyboard + mouse connected to the docking station powered down (back light on keyboard went off and could not be turned on) however the Num lock light was on.
I'm afraid that I burned the Arduino - how do I verify if that is the case.
The "ON" LED is lit up when plugged in

Ok, I have no idea what the hell is this, but when I double-press the reset button (while connected/powered on ofc) it works again.
This can be seemingly cycled - press once and it goes wrong, press twice and it's ok again... round and round. Seems more like some retarded "feature"


2 Arduino Unos Connected with 1-Wire and Receiver Pin getting Stuck High I am trying to accomplish 1-wire communication between 2 Arduinos and so I wanted to start off by having 1 Arduino toggle a digital output pin and have the other read the state of that pin. To accomplish this, I have 2 computers with Arduino IDE installed and each one is connected to one Arduino Uno. Both Arduino Uno's are connected with a single male-male jumper cable on Pin 13 of the header. I am watching the state of the pin by looking at the prints in the Serial Console on both computers.

Here is a diagram of my setup:

Computer1 ---> Arduino1[Sender] --------> Arduino2[Receiver] -----> Computer2

The problem I have is that I am seeing when I first start both Arduinos - the sender is definitely toggling the output pin high->low->high forever - but the receiver Arduino only shows its input pin as toggling for a few seconds and then it gets stuck high. Sometime later, it may go low for 1 iteration, but then sticks at high again. What is going on? I would expect to see the sender and receiver show high->low->high forever. The code seems simple but I must be doing something wrong - thanks for your help.

Sender Code:

int led = 13; // Comm Pin

// Setup pins
void setup() {

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

  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);

}

void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.println("high");
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  Serial.println("low");
  delay(1000);               // wait for a second
}

Receiver Code:

int led = 13; // Comm Pin

// Setup pins
void setup() {

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

  // Pin is an input - normal state high
  pinMode(led, INPUT);

}
void loop() {

  // Put your main code here, to run repeatedly:
  Serial.println(digitalRead(led));
  delay(1000);

}

You should add a random delay in setup of receiver and reduce the sampling time of the receiver to 200ms.

That said, digital communication is an INSANELY EXTREMELY complex process, especially on the physical layer. This is not the correct way for two arduinos to digitally communicate.

Unless you are a teacher and are trying to demonstrate why this would fail, (not criticising), you mustn't use it.

You should use the Arduino wire library to establish communication instead. You can send whole integers, and it's totally reliable (it uses hash checks, guaranteeing correct communication even at 1152000 baud). As a comparison, you're at 1 baud.

You can get a tutorial here: http://www.instructables.com/id/I2C-between-Arduinos/.


Replacing several pinMode() and digitalWrite() pins with an array I'd like to 'clean up' some code that involves several pinMode() and digitalWrite() lines by using a single line of an array. I'm very new to both arrays so I'm a bit confused. The following examples are sections from code that controls a 4 digit, 7 segment LED.

// Define display pins
// Digit pins (common cathode)
int digit1 = 13; //Display pin 1
int digit2 = 12; //Display pin 2
int digit3 = 11; //Display pin 6
int digit4 = 10; //Display pin 8
// Segment pins
int segA = 2; //Display pin 14
int segB = 3; //Display pin 16
int segC = 4; //Display pin 13
int segD = 5; //Display pin 3
int segE = 6; //Display pin 5
int segF = 7; //Display pin 11
int segG = 8; //Display pin 15

void setup() {
  pinMode(segA, OUTPUT);
  pinMode(segB, OUTPUT);
  pinMode(segC, OUTPUT);
  pinMode(segD, OUTPUT);
  pinMode(segE, OUTPUT);
  pinMode(segF, OUTPUT);
  pinMode(segG, OUTPUT);

  pinMode(digit1, OUTPUT);
  pinMode(digit2, OUTPUT);
  pinMode(digit3, OUTPUT);
  pinMode(digit4, OUTPUT);
}

#define SEGMENT_ON  LOW
#define SEGMENT_OFF HIGH

  switch (numberToDisplay){

  case 0:
    digitalWrite(segA, SEGMENT_ON);
    digitalWrite(segB, SEGMENT_ON);
    digitalWrite(segC, SEGMENT_ON);
    digitalWrite(segD, SEGMENT_ON);
    digitalWrite(segE, SEGMENT_ON);
    digitalWrite(segF, SEGMENT_ON);
    digitalWrite(segG, SEGMENT_OFF);
    break;

Defining pins:

I'm pretty sure the code below is the correct way to store the pins as an array (but please correct me  if I'm wrong).

digitPins[] = {13 12 11 10};
segPins[] = {2 3 4 5 6 7 8};

pinMode():

I understand I could use a for loop to set the pin modes but is there an even simpler way? Would something like this work?

pinMode(digitPins[], OUTPUT);
pinMode(segPins[], OUTPUT);

digitalWrite():

I could access the appropriate pin from the array to use in digitalWrite() like the code below but that would result in the same number of lines of code (and be even more confusing). Is there another option?

digitalWrite(segPins[1], HIGH);

the correct way to store the pins as an array

Your array initializers are almost right; you just need to separate the values with commas:

digitPins[] = {13, 12, 11, 10};
segPins[] = {2, 3, 4, 5, 6, 7, 8};

You will need to call pinMode() in a loop; it doesn't accept arrays as arguments.

  How about for digitalWrite() where its a mix of HIGH and LOW?

There are (at least) two ways: Make arrays of HIGH and LOW values, matching the digitPins[] and segPins[] arrays one-for-one, respectively. Or for easier maintenance, declare a data structure (struct) of a pin # and a value; make an array of those. It's a bit more complex but also more useful. So, for example:

typedef struct {
    uint8_t pinNum;
    bool pinVal;
} pinInit_t;

pinInit_t digitPins[] {
    {13, HIGH},
    {12, LOW},
    {11, LOW},
    {10, HIGH}
};

void setup() {
  // put your setup code here, to run once:
}

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

struct is short for "data structure"; it lets you combine data of different types into a single named and addressable unit. typedef declares a new data type, and says "Don't allocate any memory just now; this (pinInit) is just a description. I'll use it later on." It makes pinInit a named data type, usable wherever you can use a native data type AND a multi-valued data type (such as an array) is permissible.

Thus, we can make an array of pinInits (pin-# / boolean-value pairs) just by using the name of the new type.

Then your initializing code might look like:

uint8_t i;
for( i = 0; i < sizeof(digitPins)/sizeof(pinInit_t); ++i ){
   pinMode(digitPins[i].pinNum, OUTPUT);
   digitalWrite(digitPins[i].pinNum, digitPins[i].pinVal);
}

The expression sizeof(digitPins)/sizeof(pinInit) evaluates to the number of initializers (# of bytes in the array / # of bytes in one array member).

The expression digitPins[i].pinNum means: "in the pinInit array digitPins, get the i-th element..." (remember, this is a pair of values), "... and take value of the member "pinNum". A little more complex, the first time we think about it, but look at how easily the array reads. And a hint about reading that expression: I read it backwards: "the pinNum member of the i-th element of the digitPins array."

Tomorrow, or next month, when we need another pin, no need to update 2 arrays (remembering of course, to keep them in sequence with each other!); just add another 2-valued element to the one digitPins[] array.

func(){
   boolean pins[] ={ 1,1,1,1,1,1,0};
   for(int i=0; i<7;i++)`
   digitalWrite(segPins[i], pins[i]);
}

thats all :)


easy_install pip on Arduino Yun fails I want to install pip on the Yún which is running Linino OS but every time I execute the standard steps for opkg i.e.

# opkg update
# opkg install distribute
# okpg install python-openssl
# easy_install pip

Error

Searching for pip
Reading http://pypi.python.org/simple/pip/
Couldn't find index page for 'pip' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
No local packages or download links found for pip
error: Could not find suitable distribution for Requirement.parse('pip')

What is the reason behind this?

Kernel Information

Linux Arduino 3.3.8 #1 Fri Nov 14 08:57:34 CET 2014 mips GNU/Linux

Found this Arduino Forum Thread helpful.

# wget \
https://pypi.python.org/packages/source/p/pip/pip-6.0.8.tar.gz#md5=2332e6f97e75ded3bddde0ced01dbda3\
  --no-check-certificate
# easy_install pip-6.0.8.tar.gz

Apparently the PyPi Package Site is now HTTPS and hence --no-check-certificate option should be used. Also MD5 Checksum of the package needs to attached in the link in order to avoid a HTTP 404 Error

Try to use:opkg update  opkg install python-pip
or python-pip3


Can I make a USB Device with only data output This is about how USB ports/devices work

Lets say i have a USB port on my computer

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

1) Would I need to connect it to both D+ and D- so it forms a circuit in order for the USB port to read the data? (or would the data simply be read and then disappears so I don't have to worry about two wires?)

If Yes: 2) If I manage to forcefully push electricity through the wire onto the Data pins, would I only need one wire?

Else: 3) is this physically impossible and the whole universe would explode if I tried?

USB is a host-managed protocol. A USB device must be able to receive in order to operate, since the host notifies the device when it should send data back to the host.

The D+ and D- lines are not independent; the signaling state of the line is determined by examining both lines regardless of whether the host or the device is transmitting.

USB Made Simple

Your goal is stated as "send without being able to receive" but if you change that to "send without needing to receive" then that can be accomplished.  (You need both data pins for a serial connection in any case)

I do it all the time so I can have an Arduino with ADC pins to measure voltages then feed it to the USB serial port on a Raspberry Pi.

Just use the cable that you program the Arduino with.  (I bought a 15 foot cable from one of the usual sources so my Arduino can be near the voltage source and the Pi can be at a distance)

Anything you Serial.println on the Arduino will go to the Pi.

You can read from it on the Pi like so:

import serial
ser=serial.Serial("/dev/TTYUSB0,9600)

then

while True :
    linein = ser.readline()
    if len(linein)<10 : continue
        /* then do stuff with the input */

I even have the Arduino IDE on the Rpi so I can change the programs of either  at any time.  All of this is remote from me, so I use RDP via WiFi to connect to the Pi.

Total control without leaving my chair.

: When I connect it to my Win7 computer it gets assigned a COM port - and I go to Device Manager to find out which one, initially.  Then even through subsequent reboots it stays the same.


How many sensors can be supported by a single Arduino unit? I am a beginner in the Arduino world. I made some basic projects of the book that comes with the starter kit (it's was borrowed by a friend of mine) and also I used a humidity, a temperature sensors and a LCD display.

I want to buy an Arduino Uno for measure room temperature, humidity, carbon monoxide, carbon dioxin and maybe a couple more variables. I will to use 4 sensors, 1 buzzer, 1 LCD display and 1 ESP8266 serial WIFI wireless module.

After this work I will add for functionalities but as I have a lot of components I am not sure if the Arduino Uno can supports them because it has a limited quantity of pins.

Do I need an Arduino with more pins? what if I use all these pins and I need more? Can the Arduino Uno be expanded with more pins?

As the Arduino Uno is a very small computer, can its processor support all these components and their operations?

An Uno has more than enough pins for the devices you described.

A DHT22 Relative Humidity and Temperature sensor needs only one digital pin for both variables.
An MQ-7 Carbon Monoxide sensor needs one analog pin.
An MG-811 Carbon Dioxide sensor needs one analog pin (and an amplifier).
A Piezo buzzer needs one PWM pin.
The LCD with a Hitachi interface needs four digital pins.
The ESP module needs two digital pins.

That's 7 digital pins, one of which needs to be a PWM pin, and 2 analog pins. I did not make any choices about best or cheapest devices, just ones I either knew about or could find quickly by searching. But with this pin requirement doesn't come close to exhausting the available pins on an Uno so there's plenty of capacity left unassigned for you to make other choices that might require different interfaces or more pins.

You can also use arduino's Analog pins as digital pins.....
by doing this you have 18 pins to use....
wait a minute you are using esp8266 with your arduino, then you don't need any sensor just connect your esp8266 with any website which tells all that things that you want and just simply read the data from the webpage and show in the lcd display.....


Arduino Nano USB Serial Bypass I have a Nano clone here, that sporadically fails to get detected by my banana pi. This is annoying, because it works for days and hours, but fails to work randomly.

The Nano gets it's own power via VIN and thus should have enough power.

I thought of bypassing the FTDI and make a Serial connection via 2 Wires. Alternatively: Is there a way to force the arduino to use external Power over USB. I have the feeling, the the arduino wrongly decides, that USB is the better power source and uses it, causing the errors ( device not accepting address 21, error -62 )

P.S.: There is also a touch-screen connected to the banana pi via USB. Whatever port I use, It works and never failed. Just the Nano fails from time to time.

To answer this question

The arduino in question was broken. Shortly after asking I was not even able to connect it to my PC successfully. I replaced it with a new one and everything runs smoothly now for months.

Since this unit survived a whole product development-process I am not surprised at all. In fact I had three and expected one to get killed in action.


Is it possible to run two for loops separated? I have three funtion which describe the brightness of three LEDs. I want the seconde loop run 1 second after the first one and the third 1 second after the second one. One loop needs approximately 5 seconds. So basically I need to run three loops separated. How is this possible?

Update:
So I have this code running which I can compile but does not work:

int LED = 3;
int LED2 =10;
int LED3 = 9;

bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

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

void loop()
{
// Update loop enablers.
switch(periodIndex)
{
case 0:
 loop1state = true;
 loop1index = 0;
 break;

case 1000:
 loop2state = true;
 loop2index = 0;
 break;

case 1500:
 loop3state = true;
 loop3index = 0;
 break;

case 4000:
 periodIndex = 0;
 break;
}

if (loop1state)
{
 for (loop1index = 0; loop1index<255; loop1index++){
  analogWrite(LED,loop1index);
 }

 loop1state = loop1index < 256;
 }

 if (loop2state)
 {
 for(loop2index = 0; loop2index<255; loop2index++)
 {
  analogWrite(LED2,loop2index);
 }

 loop2state = loop2index < 256;
}

 if (loop3state)
 {
 for(loop3index = 0; loop3index<255; loop3index++)
 {
  analogWrite(LED3,loop3index);
 }
 loop3state = loop3index < 256;
 }
 delay(10);
 }

No, but there is a solution to put the action in one loop (main loop).

If I understand you well, you have the following scheme:

Time[s]
0..1     Loop 1
1..2     Nothing
2..3     Loop 2
3..4     Nothing
4..5     Loop 3

Define a variable that keeps track of the time.
Check against the current time (millis) and when within the correct 'range' perform an action.
After 5 seconds start over again.

uint32_t lastTime = -1;

void loop()
{
    if (lastTime == -1)
    {
        lastTime = currentTime; // Initialization, can be done in setup too
    }

    uint32_t diffTime = millis() - lastTime;

    if (diffTime < 1000) // 0..1 sec
    {
        DoLoop1();
    }
    else if (diffTime < 2000)
    {
         // Do nothing();
    }
    else if (diffTime < 3000)
    {
       DoLoop2();
    }
    else if (diffTime < 4000)
    {
        // Do nothing
    }
    else if (diffTime < 5000)
    {
       DoLoop3();
    }
    else // diffTime >= 5000
    {
         lastTime == currentTime; // Reset after 6 s
    }
}

Update

Since you need all three loops together (and mixed), it's easier to define some variables.

bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

Too bad I don't know the conditions when a loop starts, but let's say each iteration is 10 ms, and loop 1 starts immediately, loop 2 after 1000 ms, loop 3 after 1500 ms. After 3000 ms it starts all over.

void loop()
{
  // Update loop enablers.
  switch(periodIndex)
  {
  case 0:
     loop1state = true;
     loop1index = 0;
     break;

  case 1000:
     loop2state = true;
     loop2index = 0;
     break;

  case 1500:
     loop3state = true;
     loop3index = 0;
     break;

  case 4000:
     periodIndex = 0;
     break;
  }

  if (loop1state)
  {
     DoLoop1(loop1index++);
     loop1state = loop1index < 256;
  }

  if (loop2state)
  {
     DoLoop2(loop2index++);
     loop2state = loop2index < 256;
  }

  if (loop3state)
  {
     DoLoop3(loop3index++);
     loop3state = loop3index < 256;
  }

  delay(10); // 10 ms
}

Note, not tested, but the idea shold be clear

New update

You should not do a full loop during each switch, but only one iteration of the loop.

I did not run the sketch, just out of my head.

Some tips: print out the variables during each loop, so you get a clear idea what is happening (so all loop states and indices, and the periodIndex).

int LED = 3;
int LED2 =10;
int LED3 = 9;

bool loop1state, loop2state, loop3state; // True if running, false if off
int  loop1index, loop2index, loop3index; // Iterator values
int  periodIndex = 0; // starting with 0, increasing every 10 ms

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

void loop()
{
  // Update loop enablers.
  switch(periodIndex)
  {
  case 0:
    loop1state = true;
    loop1index = 0;
    break;

  case 1000:
    loop2state = true;
    loop2index = 0;
    break;

  case 1500:
    loop3state = true;
    loop3index = 0;
    break;

  case 4000:
     periodIndex = 0;
     break;
  }

  if (loop1state)
  {
    analogWrite(LED,loop1index++);
    loop1state = loop1index < 256;
  }

  if (loop2state)
  {
    analogWrite(LED2,loop2index++);
    loop2state = loop2index < 256;
  }

  if (loop3state)
  {
    analogWrite(LED3,loop3index++);
    loop3state = loop3index < 256;
  }

  periodIndex++;
  delay(10);
}

So I have this code running which I can compile but does not work:

because it is wrong.

try something like this instead:

  time_elapsed = millis() / 1000 - start_time;  //time past start time, in seconds
       if (time_elapsed < LOOP1_ENDTIME) loop1();
  else if (time_elapsed < LOOP2_STARTTIME) do_nothing();
  else if (time_elapsed < LOOP2_ENDTIME) loop2();
  else if (time_elapsed < LOOP3_STARTTIME) do_nothing();
  ...
  else start_time+=TOTAL_TIME; //update start time

edit 2:

so here is the above code in action.

three simple tasks: loop1() flips D12, loop2() flips D13 and loop3() flips D8.

The time duration + gaps for those tasks are specified by the following macros:

#define LOOP1_DURATION  5  //time in x100 ms for easier simulation
#define LOOP1_GAP       1
#define LOOP2_DURATION  4
#define LOOP2_GAP       2
#define LOOP3_DURATION  3
#define LOOP3_GAP       6

from those macros, I built the ending and starting time used in the code above.

the code is long-term error free and will never lose track of time.

As you can see, it is essentially a fancy way of executing the following:

  do {loop1();} while (loop1's time isn't up);
  do {nothing();} while (loop1's gap time isn't up);
  do {loop2();} while (loop2's time isn't up);
  do {nothing();} while (loop2's gap time isn't up);
  ...

the advantage with my implementation is that each loop run is very quick and you can execute other tasks as well.

But the general idea is the same.


ESP8266 SPIFFS file not found I have a simple HTML file that I have uploaded as sketch data using the ESP8266 sketch data upload tool in arduino IDE. The file is 7k in size.

In the set up, I refer to the following function to read the file:

String readTemplatefile(){
  String retval ="";
  File fr = SPIFFS.open("/templatecfg.htm", "r");

  if(!SPIFFS.exists("/templatecfg.htm")){

    Serial.println("Template file not available ");
    }
    while (fr.available()){
        retval += char(fr.read());
      }

fr.close();
Serial.println("Template file = ");
Serial.println(retval);
return retval;
}

I always get 'Template file not found'. I have

SPIFFS.begin();

at the beginning of the setup function

My board is an ESP8266EX. I have wondered if it the flash size settings in the IDE that could cause this not to be found. Can anyone offer any advice on this issue. I have tried lots of different combinations of Flash size and SPIFF sizes without any luck.

Thanks in advance to any help.

SPIFFS will always claim to successfully open a file that begins with a slash even if that file does not exist.  Remove the leading slash.

@dandavis Yes, I had SPIFFS.begin() in my setup routine.

I ran a sample sketch and was able to see the a file on the device, so I routed round the code some more and found than an included library was ending SPIFFS after it had performed a file read. This was the issue. Thanks all for your consideration, but the code I had was fine, just the included library was mis-behaving.


Wire.h not found newliquidcrystal The arduino IDE can't seem to find the wire.h file when i'm using the new liquid crystal library. Does anyone know how to solve this? here is the code i'm using and the error message:

/*-----( Import needed libraries )-----*/
#include <Wire.h>  // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>

/*-----( Declare Constants )-----*/ /*-----( Declare objects )-----*/ // set the LCD address to 0x27 for a 16 chars 2 line display // A FEW use address 0x3F // Set the pins on the I2C chip used for LCD connections: //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

/*-----( Declare Variables )-----*/ //NONE

void setup()   /*----( SETUP: RUNS ONCE )----*/ {   Serial.begin(9600);  // Used to type in characters

  lcd.begin(16,2);   // initialize the lcd for 16 chars 2 lines, turn on backlight

// ------- Quick 3 blinks of backlight  -------------   for(int i = 0; i< 3; i++)   {
    lcd.backlight();
    delay(250);
    lcd.noBacklight();
    delay(250);   }   lcd.backlight(); // finish with backlight on

//-------- Write characters on the display ------------------ // NOTE: Cursor Position: (CHAR, LINE) start at 0     lcd.setCursor(0,0); //Start at character 4 on line 0   lcd.print("Hello, world!");   delay(1000);   lcd.setCursor(0,1);   lcd.print("HI!YourDuino.com");   delay(8000);

// Wait and then tell user they can start the Serial Monitor and type in characters to // Display. (Set Serial Monitor option to "No Line Ending")   lcd.clear();   lcd.setCursor(0,0); //Start at character 0 on line 0   lcd.print("Use Serial Mon");   lcd.setCursor(0,1);   lcd.print("Type to display");

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/ {   {
    // when characters arrive over the serial port...
    if (Serial.available()) {
      // wait a bit for the entire message to arrive
      delay(100);
      // clear the screen
      lcd.clear();
      // read all the available characters
      while (Serial.available() > 0) {
        // display each character to the LCD
        lcd.write(Serial.read());
      }
    }   }

}/* --(end main loop )-- */

Here is the compiler output

  Arduino: 1.6.7 (Windows 10), Board: "Arduino Nano, ATmega328"

  C:\Users\martin\Documents\Arduino\libraries\LiquidCrystal\I2CIO.cpp:35:26:
  fatal error: ../Wire/Wire.h: No such file or directory

  #include <../Wire/Wire.h>

                      ^

  compilation terminated.

  exit status 1 Error compiling.

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

The liquid crystal library has to be installed in the same folder as the wire library:

libraries/Wire/Wire.h (etc)
libraries/LiquidCrystal/LiquidCrystal_I2C.h (etc)

There is a hard-coded path in the liquid crystal library pointing to the wire library that is relative to where the liquid crystal library is, which is done to get around the problem that the Arduino library doesn't recurse libraries. It's not actually needed since including the Wire library in the IDE is enough to tell it where to find it for the liquid crystal library, so I don't really know why they did it that way.

Don't know if you could resolve the problem. I am using PlatformIo and import the LiquidCrystal library (i used li. Doing on this way i got error finding Wire.h library but appending this line on platformio.ini file:
(after framework = arduino)

lib_deps = Wire


Arduino Yun does it have a RTC? Does the Arduino Yun does it have a RTC?

And if so is it connected to the Atheros AR9331 or the ATmega32u4?

If there there is no RTC, can I connect a DS1307 to the Atheros AR9331?

the Yún doesn’t have a real time clock IC on board, so it can’t keep time when is powered off. Instead, it synchronizes with time servers automatically when it powers up and connects to a network using NTP.

(Arduino Blog)

Therefore, the Yun does not have a onboard RTC.

  If there there is no RTC, can I connect a DS1307 to the Atheros AR9331?

Probably not. It comes in a LPCC package, which has the solder joints on the bottom. This needs to be soldered by reflow. The Yun does not have any pins connected directly to that chip. You're probably thinking of the ATmega32u4, the actual Arduino chip. The other one is for a router.

To get the time, you have two options:

Use the time from the time server

A few notes:

  The Yún must be connected to a network to get the correct time. If you used the web-based WiFi interface to configure the Yún for the network, make sure you've selected the proper time zone.

Connect it to a DS1307 (I find this Adafruit tutorial helpful) You'll need only two pins to use this board. One note: there is a way to connect up to 121 I2C devices using these two pins. However, that gets a little more complicated.

What happens with your Arduino YUN is that it has an internal clock which sincronizes with a computer (at least this is what I do).
However I have read that it can be automatically but I could not do that; have you got a probable solution?


Did I just brick my ATMEGA 2560? I bought an ATMEGA2560 on eBay and programmed it with Arduino IDE 1.6.9 using the USB cable, and the LED blinked as expected - All well and good.

Now I wanted to program the mega from my UNO as follows:

Uploaded ArduinoISP to the UNO
Changed the Board to Mega2560 and changed the Programmer to Arduio as ISP
Connected the two ICPS sockets with a 6 wire cable, where pin 5 on the UNO ICPS is cut and instead connected to D10 on the UNO
Upload the Blink sketch: IDE says Uploading for a minute, then some errors:

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

5) Upload Using Programmer: Activity on the UNO (RX/TX) and the LED on the mega lights constantly - And I can no longer program the mega using the IDE

Any pointers to what I did wrong and how to fix it?
Best regards

Ah, the problem seems to be in the IDE - Something with the fuses when programming the mega (I won't even pretend to understand that yet).
I upgraded to 1.6.12 and everything works like a charm.

Best regards
Stefan


Question regarding Servo including Serial monitor display I tried to make code following your instruction about mills,
and it looks like this. Unfortunately, it is not working. Is there problem with my code?

Here is my code:

#include <LiquidCrystal.h>
#include<Servo.h>

Servo myservo;  // create servo object to control a servo

// These constants won't change. They're used to give names to the pins used:
const int analogInPin1 = A0;  // Analog input pin that the photosensor is attached to
const int analogInPin2 = A1;  // Analog input pin that the photosensor is attached to
const int analogInPin3 = A2;  // Analog input pin that the photosensor is attached to
const int analogInPin4 = A3;  // Analog input pin that the photosensor is attached to
int sensorValue1;
int sensorValue2;
int sensorValue3;
int sensorValue4;
unsigned long m;

//declare counter as an input
int Chactr =0;
int Disctr =0;

byte state;

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write(0);  // back to 0 degrees.
  delay(1000); // wait for a second.
  pinMode(13, OUTPUT); // initialize digital pin 13 as an output.
  Serial.begin(9600);  // initialize serial communications at 9600 bps:
  lcd.begin(16,2);

  delay(5000);
}

void loop() {

  // read the analog in value:
  sensorValue1 = analogRead(analogInPin1);
  sensorValue2 = analogRead(analogInPin2);
  sensorValue3 = analogRead(analogInPin3);
  sensorValue4 = analogRead(analogInPin4);

  delay(3000);

  // print the results to the Serial Monitor:
  Serial.print("sensor1 = ");
  Serial.print(sensorValue1);
  Serial.print("\n");

  Serial.print("sensor2 = ");
  Serial.print(sensorValue2);
  Serial.print("\n");

  Serial.print("sensor3 = ");
  Serial.print(sensorValue3);
  Serial.print("\n");

  Serial.print("sensor4 = ");
  Serial.print(sensorValue4);
  Serial.print("\n");

  Serial.print("Led State:  ");
  Serial.println(state);
  Serial.print("\n");

  if (sensorValue1 >=569 && sensorValue2 >=520 && sensorValue3 >=419 && sensorValue4 >=250)
  {
    m=(millis()+60000);
  }

  if(sensorValue1 <=568 && sensorValue2 <=519 &&sensorValue3 <=418 && sensorValue4 <=249)
  {
    m=0;
  }

  if (sensorValue1 >=569 && sensorValue2 >=520 && sensorValue3 >=419 && sensorValue4 >=250 && m==millis())
  {
    state=1;
    delay(5000);
    digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
    delay(5000); // wait for a second

    myservo.attach (9);
    myservo.write(30);
    delay(3000);
    myservo.write(0);
    delay(3000);

    myservo.detach ();
    delay (1000);

    Disctr = Disctr + 1;

    delay(900);

    Serial.print("Battery Full: Discharge ON");
    Serial.print("\n");
  }
  else if (sensorValue1 ==0 && sensorValue2 ==0 && sensorValue3 ==0 && sensorValue4 ==0 )
  {
    m=(millis()+60000);
  }

  if(sensorValue1 >=1 && sensorValue2 >=1 && sensorValue3 >=1 && sensorValue4 >=1)
  {
    m=0;
  }

  if(sensorValue1 ==0 && sensorValue2 ==0 && sensorValue3 ==0 && sensorValue4  ==0 && m==millis())
  {
    state=0;
    delay(5000);
    digitalWrite(13, HIGH ); // turn the LED On by making the voltage high
    delay(5000); // wait for a second

    Chactr = Chactr + 1;
    delay(900);

    Serial.print("Battery Empty: Charging ON");
    Serial.print("\n");
  }
  {
    lcd.setCursor(0,0);
    lcd.print("Charge Cycle: ");

    lcd.setCursor(13,0);
    lcd.print(Chactr);

    lcd.setCursor(0,1);
    lcd.print("Discha Cycle: ");

    lcd.setCursor(13,1);
    lcd.print(Disctr);

    delay(1000);
  }
}

So what you want to do is be able to activate the servo when 4 green bars appear over the course of one minute correct?

I think you would need to create three if statements and one new variable. The first if statement will be, if it detects four green bar, then m=(millis() + 60000). Then you will need to nest another if statement in here to say if it detects ONLY three bar, then m = 0.
Your third if the statement is if it detects the four green bars AND m == millis() then the servo will activate.

This is how I would do it, but I am not very experienced. I'm pretty sure others will have a cleaner and simpler code but this should work.


Controlling water temperature accurately I have following setup:

Arduino Duemilanove
Small water heater connected with optical relay (PWM is ok)
Waterproof DS18B20 temperature sensor
Unknown amount of water (but temperature sensor and heater are always underwater).

How can I accurately control water temperature, based on temperature sensor readings? By accurately, I mean up to accuracy of temperature sensor (in this case, ±0.5°C). Everything should run on Arduino, so no additional data storage or processing power is available. For debugging, I can obviously use computer.

I have tried running PID, but it seems really hard to

Avoid overshooting - going over target temperature either initially, or when (cold) water is added
Stabilize properly after adding cold water.

You need to know the response time of your system and the repeatability of your measurements to characterize your data (establish confidence). I suggest taking samples and average them before turning the heater back on.

Imho, water will not happily stay within 0.5°C. Can you allow for coarse and fine modes? Use a higher PWM for great differences and then lower PWM for when close to target.

Once homed in on your target, there are a few means you can try to improve temperature stability. While pre-built things like PID work for many, I normally implement functionality like this manually.

You need to keep the amount of water being heated constant.  The rate at which the water temperature increases will change when you vary the water amount (adding cold water like you mentioned).  A proportional-integral-derivative controller (PID) works off observing the derivative (rate of change) of the variable you are trying to control.  Your PID will never work properly if the rate of temperature change is not (reasonably) constant.

Look into specific heat of water, mainly the equation Q = cmdT.  Q is the heat added, which I would assume is constant in your setup.  m is the mass of the substance being heated (must be kept constant!). c is the specific heat of water, which is 4.186 Joules/gram*degreeC.  If Q, m, and c are constant then dT, the rate at which your water temp will rise will also be constant (in reality c varies slightly with temperature but I'd say this can be ignore if you're working from 0-100C).  Try tuning your PID with a constant water amount and you may get better results.

What water heater are you using?  I am currently doing something similar but trying to use a hot plat from the chemistry lab and experiencing huge overshoots. Ive considered switching to an aquarium heater but would like to know what you're using?

-Matt


Arduino (Or Raspberry Pi) As HID Device I have an Arduino Uno and A Raspberry Pi B+. I was wandering how I could use either as a Programbel HID Device (EX: https://srlabs.de/badusb/). The Reason I ask under the arduino section is I want to preferably use it. If not I can use either.

The Uno cannot be used as a HID device through the on board USB. You might be able to use the V-USB Library to be a HID device using the digital IO pins. See this tutorial.

There are several arduino compatible boards that do can act as a HID device natively. Most boards built around the ATMega32u4 can be a HID device.  For example the Arduino Micro

See this question about the Raspberry Pi.


Send HTTP get request from GSM SIM800c and Arduino I am trying to send Get request from my GSM Module but after connecting to server it is not responding any thing

#include <SoftwareSerial.h>
SoftwareSerial myGsm(2,3);
void setup()
{
myGsm.begin(9600);
Serial.begin(9600);
delay(500);
myGsm.println("AT+CGATT=1");
delay(200);
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR,connection type is GPRS
delay(1000);
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"APN\",\"wap.mobilinkworld.com\"");//setting the APN,2nd parameter empty works for all networks
delay(5000);
printSerialData();
myGsm.println();
myGsm.println("AT+SAPBR=1,1");
delay(10000);
printSerialData();
myGsm.println();
myGsm.println("AT+SAPBR=2,1");
delay(10000);
printSerialData();
myGsm.println("AT+HTTPINIT");
delay(2000);
printSerialData();
myGsm.println("AT+HTTPPARA=\"URL\",\"http://sensor.somee.com/api/Data/GetData?SensorID=1\"");// setting the httppara,
delay(1000);
printSerialData();
myGsm.println();
delay(10000);//the delay is important if the return datas are very large, the time required longer.
printSerialData();
delay(9000);
printSerialData();
delay(1000);
Serial.println("done ");
printSerialData();
}
void loop()
{
}
void printSerialData()
{
while(myGsm.available()!=0)
Serial.write(myGsm.read());
}

and the Out put is

AT+CGATT=1

OK
AT+SAPBR=3,1,"CONTYPE","GPRS"

OK
AT+SAPBR=3,1,"APN","wap.mobilinkworld.com"

OK

AT+SAPBR=1,1

OK

AT+SAPBR=2,1

+SAPBR: 1,1,"10.209.122.68"

OK
AT+HTTPINIT

OK
AT+HTTPPARA="URL","http://sensor.somee.com/api/Data/GetData?Sen
done

You haven't instructed the module to make a request yet.
With the AT+HTTPPARA command, you are just configuring the request you want to make. In your case, you just specified the URL you want to call.
Next, you have to send
AT+HTTPACTION=1

to make the actual request using the HTTP GET method, and then you can read the HTTP response using
AT+HTTPREAD

Keep in mind that after AT+HTTPACTION you will receive an unsolicited result code in the format
+HTTPACTION: <Method>,<StatusCode>,<DataLen>

this will happen after the module will actually do the request and will have the response.

You should place the code to communicate (which is a recurring task) into the loop (and do this without blocking delay()s. Using delay stops the CPU so whatever comes to the buffer is probably not processed.
Read about the difference of placing code in the setup and the loop in the Arduino basic documentation.Never use delay in communiction scenarios (except for intializing hardware in setup) see example blinkwithoutdelay in ArduinoIDE


Field Hockey Ball Tracker I'm brand new to development and planning a project with my daughter to track speed and time in motion of a ball.

Example, ball is at rest. It is then put into play, timer starts, and speed is tracked until ball is at rest. Is is possible to get accurate data with relatively inexpensive sensors?

Data would look like:
Moved 19 consecutive seconds, average speed during that time=33mph.

Direction, elevation, acceleration changes, etc. would be ignored at this time. To start we just want average speed over time in use. We're having a bit of trouble deciding between accelerometers vs gyro vs magnetometer (or combination)

Any assistance (even links to where to learn) would be greatly appreciated

An accelerometer is the way to go. There will be a fair amount of math to go thru in order  to convert the acceleration value into speed. I can't explain it better than this answer.

An gyro would give you the angular rate on the ball and the magnetometer could give you the ball orientation relative to the magnetic north.


How to connect IR Transmitter and Receiver Module? The IR Transmitter and Receiver module has both receiver and transmitter in same board. I tried Arduino IR Remote library example to decode Remote signal using below connection, but its not working.

IR MODULE:   ARDUINO
Ground   ->  Ground
5V       ->  5V
RXD      ->  PIN 11
TXD      ->  PIN 10

The board also has 3 pin connector (Gnd, 5v, S). How to connect pins to Arduino to receive/decode and send IR signals? (Can't able to find any tutorial for this type of board)

Example Code:

#include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  delay(100);
}

The device in the question is commonly sold on aliexpress.com and the likes of ebay.com.  As you might guess there is little in the way of documentation.  Without documentation we can only speculate.  As such, I expect that the module handles all the modulation and demodulation.  It is likely all you need to do is use the Arduino serial library and connect the TX and RX to the Arduino's RX and TX pins.  However, if you would like to preserve the function of these pins for use with the Arduino Uno's USB port, you can use the Arduino software serial library which will "emulate" a serial port an an unused (alternate) set of pins.

(This is an example of a similar well documented device with access to the schematic and source code.  Armed with this type of knowledge you can turn this device into what ever you want.  In other words, you probably don't even need an Arduino.  You can just program this device and be done with your project.)

For that module you dont need library for easy example for sample for send HIGH and LOW status but. it doesnt work for control IR protocol. for that you need the basic conection Just (data-gnd-Positive)   in that example data is for pin = 11


How to interface ESP8266-01 Wifi Module with Arduino Uno I have an Arduino Uno and ESP8266-01 Wifi module with me currently. So I'm going to use ESP8266 to connect to the MQTT broker to allow me publish data to other devices. However, I have a problem with uploading my sketch due to the following error:

error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I uploaded the example sketch WIFIScan provided by Arduino IDE to test ESP8266 whether working or not, so the code is not a problem. This is how I connect ESP8266 to the laptop.

The Arduino Uno is connected to my laptop through USB port.

There are so many issues when working with the ESP8266, try unplugging the Arduino, replugging and immediately reuploading. Also, make sure that you have the ESP8266 as the board selected and that you are using the right port.

Hope this works!


Arduino IDE doesn't find header file I'm trying to start with the SainSmart 4x20 serial LCD, and copied the library to the Arduino library:

So LiquidCrystal_I2C.h is included. But when I try to compile an example sketch it says

  Arduino: 1.7.0 (Windows 7), Board: "Arduino Uno"

  HelloWorld_i2c.pde:2:31: fatal error: LiquidCrystal_I2C.h: No such file or directory

  compilation terminated.

  Error compiling.

Any ideas how to fix this?

I copied the SainSmart library to the IDE's library folder, not noticing that there was already a folder named "LiquidCrystal". Apparently the files added to the existing folder are being ignored.

Renaming the SainSmart library before adding it solves the problem.

I just found a solution by myself...

You just need to replace the library folder by a new one...

In the error message it will show you which library is used and which not...

Just replace the used library to a new one...


Is there any version of arduino that can do something like serial interruption? I am using an Arduino to control servo MX18A by serial, and trying to use computer to communicate with the Arduino by another serial to send commands to Arduino and change the servo control mode. Once the computer send a message to Aruduino, I hope it could response in time because may be there is something emergency like the servo being out of control ,under which circumstance I have to change the control strategy in time.

However, it seems like Arduinos like UNO, MEGA does not have serial interruption, so once the message from computer comes, it could not response in time.

I know that judging serial.available() in every loop is one solution, but in my different servo control strategy there are many time delays, for loops and while loops, which means that I have to put serial.available() in every time delay or for loops, making the code hard to write and maintain.

It is not a case of "An Arduino" that can do serial interupts. All Arduino boards have serial interrupts, but they are already used to receive the data and store it in a buffer for you to consume when you have the time.

The Arduino API does not define any serial interrupt handling routines. That kind of thing is designed to be handled internally by the API code, not by the user. That's the whole point of the Arduino API - to abstract away such technicalities from the user.

If you want to use the serial interrupt yourself you will have to write your own serial handling code.

Or write your code in such a way that serial interrupts aren't needed.

Why not use a timer to check if any data is in the serial buffer every say 2 seconds.
The DUE has interrupts available on ALL pins so that could be a viable alternative solution.
You shouldn't use blocking code anyway, e.g. whiles and delays.


Unable to connect and configure ESP8266 wifi module with Ardunio Mega I try to connect Ardunio Mega with ESP8266 wifi module. Wiring diagram mentioned below:

I am using Ardunio IDE - For AT command test I was open COM monitor and selected 115200 baud rate and set to Both NL & CR.

But no response from ESP8266 wifi module. Response like "System read Vendor". I have changed different baud rate. But no use of it.

I don't know what I am missing out.

Please help on this.

Thanks,
Shanmuga Raja

Your ESP8266 module is most likely fried now, if your wiring diagram is any indication of your actual hardware setup.

The ESP operates at 3.3V, which means that every pin on it can receive no more than 3.3V as input. And it looks like you've directly connected the ESP's TX pin with the Arduino, without using a level shifter. The Arduino GPIO pins work on 5V logic levels.

Test this module out with a level shifter (resistor divider network, 3.3V zener, level shifter IC; pick your poison). If the ESP still doesn't respond, swap it out with a new one and repeat.


Powering 24 volt solenoid valve with Arduino uno Today I received normally closed solenoid valve which I am going to use in automated pot watering system ,
I realised the valve takes 24 dc volt as input and Arduino has maximum of 5volt , using some power booster I can convert it to some extent but I think 24 volt is too much .

So how should power 24volt solenoid valve from Arduino uno?

Since the solenoid requires higher current than the arduino can provide you can use an alternative power source for the solenoid (maybe a couple of batteries) and switch it with a TIP120 transistor.

24V AC or DC?  Relay would be good for either.

Low Rds N-channel logic level MOSFET (IRFL540) would be good for sinking DC current.


Ublox GPS with Arduino Mega 2560 not working Recently I bought a GPS module (ublox neo-6M-0-001) for my Arduino Mega 2560. I connected Vcc and Gnd (LED at GPS module glows blue and sometimes blinking).

GPS module RX port is connected to the Arduino's TX3, Port 14.
GPS module TX port is connected to the Arduino's RX3, Port 15.

As a first step I just want to print the serial data received from the GPS module:

#include "SoftwareSerial.h"

SoftwareSerial mySerial(15, 14); // RX, TX

void setup() {
  Serial.begin(9600);
  Serial.println("uBlox Neo 6M Test");
  mySerial.begin(9600);
}

void loop() {
   if (mySerial.available())
     Serial.write(mySerial.read());
}

Saldy, there is no data received from the GPS module. According to the datasheet the baud rate 9600 seems to be correct.

Do I need to configure the GPS module somehow before it delivers data? Do I need to buy an external antenna?

Thanks for your help.

The Arduino Mega 2560 has three additional hardware serial ports. Why not use one of them instead? Serial1 on pins 19 (RX) and 18 (TX).

void setup()
{
  Serial.begin(9600);
  Serial.println("uBlox Neo 6M Test");
  Serial1.begin(9600);
}

void loop() // run over and over
{
  if (Serial1.available())
     Serial.write(Serial1.read());
}

Cheers!

I am also using the sam setup i.e Arduino Mega and NEO6VM2. The GPS module works perfectly fine with a Arduino Uno but when using Mega there are no CharsRX received i.e the Mega is not receiving anything. Please I need help urgently.


Why does the PIN 13 LED of Uno R3 blink every time I upload some code? I was driving a relay from Arduino Uno R3 Pin 13. I observed that every time I upload some code the led on the board designating pin 13 would blink. I'm curious why this is so. I understand that the serial LED blinks cause there's a serial transmission but why an IO pin?

See What happens when code is uploaded using the bootloader? - the flashing is by design.

Probably the reason is to confirm that the bootloader has started.

To show that the bootloader is functioning satisfactorily to the hobbyist. Boot loader helps to upload new sketch on the chip.


DB:NO RESP Using inet.httpPOST on loop() I'm using SIM900 module + arduino uno + gsmlib.org library.

I'd like to send a string to endpoint on my API , and it worked correctly for the first time when I using inet.httpPOST function in setup(), but... in loop(), when I call that function again, it doesn't work. On serial monitor I get:

ATT: ERROR
RIC:
ERROR
DB:STARTING NEW CONNECTION
ATT: SHUT OK
RIC:
SHUT OK
DB:SHUTTED OK
ATT: OK
RIC:
OK
DB:APN OK
ATT: OK
RIC:
OK
DB:CONNECTION OK
ATT: ERROR
RIC:
xxx.xxx.xxx.xxx

DB:ASSIGNED AN IP
status=ATTACHED

http://api.com.br/mystring

ATT: OK
RIC:
OK
DB:RECVD CMD
ATT: CONNECT OK
RIC:
OK
ATT: OK
RIC:
CONNECT OK
DB:OK TCP
ATT: >
RIC:
>
DB:>
ATT: SEND OK
RIC:
SEND OK

DB:SENT

http://api.com.br/mystring

ATT: OK
RIC:
xxx.xxx.xxx.xxx
ERROR
ALREADY CONNECT
DB:NOT CONN
ATT: OK
RIC:
ERROR

ALREADY CONNECT
DB:NOT CONN
ATT: OK
RIC:
ERROR

ALREADY CONNECT
DB:NOT CONN

How can I send data to my API continuously on loop() Could someone help me?

Following is my code (SOLVED):

#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <inetGSM.h>

InetGSM inet;
TinyGPSPlus gps;
SoftwareSerial serialGps(11, 10);

/**
    setup
*/
void setup() {
  // Serial connection.
  Serial.begin(19200);
  Serial.println(F("Starting App Arduino"));

  // Turn on GPRS
  powerUpGprs();

  // Start configuration of shield SIM900 with baudrate and  connect to internet.
  if (gsm.begin(9600)) {
    Serial.println(F("\nstatus=READY"));

  // Start configuration of shield GPS NEO-6M with baudrate.
  serialGps.begin(9600);

  // Mensure and show memory usage
  Serial.println(F("\nMemory usage"));
  Serial.print(freeRam());
}

/**
   loop
*/
 void loop() {
  serialGps.listen();
  while (serialGps.available() > 0)  {
    if (gps.encode(serialGps.read())) {
      // Get GPS position and send To API
      gsm.listen();
      // if sim900 started, connect to internet
      Serial.print(F("\r\n"));
      Serial.print(F(" CONNECT TO INTERNET \r\n"));

      // GPRS attach, put in order APN, username and password.
      if (inet.attachGPRS("zap.com.br", "zap", "zap"))
        Serial.println("status=ATTACHED");
      else Serial.println("status=ERROR");
      delay(1000);
      // Read IP address.
      gsm.SimpleWriteln("AT+CIFSR");

      Serial.print(F("\r\n\r\n"));
      Serial.print(F(" GET GEOLOCATION & SEND TO API \r\n"));
      // get geolocation
      String geo;
      geo.concat("lat=" + String(gps.location.lat(), 6));
      geo.concat("&lng=" + String(gps.location.lng(), 6));
      geo.concat("&spd=" + String(gps.speed.kmph()));
      geo.concat("&gps.uuid=1");
      // send2Api
      Serial.println(geo.c_str());
      Serial.print(F("\n"));
      gsm.SimpleWriteln("AT+CIFSR");
      inet.httpPOST("api.com.br", 80, "/geolocations", geo.c_str(), "", 100);
    }
  }
}

/**
   mensure memory usage
*/
int freeRam() {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

/**
   Power up
*/
void powerUpGprs() {
  pinMode(9, OUTPUT);
  delay(100);
  digitalWrite(9, HIGH);
  Serial.println(F("\nPower Up SIM900!"));
}

Thank You!!!

Like I told you before, you have 2 instances of SoftwareSerial active, but you're allowed to listen to only one at a time (implementation rules). So you have to alternate between calling listen() on each instance; any data arriving at any port while its not the active port will be discarded. inet.httpPOST() worked in setup() because you called the function before begin()ing serialGps. Calling serialGps.begin() immediately made serialGps the active port, severing communication with the modem.

Add this line to SIM900.h in the library, under the public methods:

void listen();

Add this method to SIM900.cpp:

void SIMCOM900::listen(){
   _cell.listen();
}

Save the files and add gsm.listen() right before gsm.SimpleWriteln("AT+CIFSR"); in loop().
Re-initialize GPRS, like you did in setup() with attachGprs(), right after gsm.listen() in loop().
Make serialGps.listen() the last  statement in loop() immediately after the inet.httpPOST() call. Use braces to enclose the body of the while loop.

Hopefully this should solve your problem.

I had similar problem. I have added gsm.begin() method at the end of the loop, and it has solved my problem!!

Seems like you can't send multiple http requests with single gsm session.
Relevant parts of setup() and loop() methods are shown below:

void setup()
{

Serial.begin(9600);
Serial.println("GSM Shield testing.");

if (gsm.begin(2400)){
  Serial.println("\nstatus=READY");
  started=true;
}
else Serial.println("\nstatus=IDLE");

}

void loop()

{
   if(started){
      if(inet.attachGPRS("internet.wind","",""))
        Serial.println("status=ATTACHED");
      else
        Serial.println("status=ERROR");

      if(inet.httpPOST(server,port, path,parameters,msg, 50)){
          Serial.println("Data sent to server succesfully!");
      }
      else{
        Serial.println("Failed to send data to the server");
      }
 }

 if (gsm.begin(2400)){
  Serial.println("\nstatus=READY");
  started=true;
}
else Serial.println("\nstatus=IDLE");

};


Why wifiManager.setTimeout(60) is not working? in this code I am using wifiManager.setTimeout(60); so that when it fails to connect to the wifi it should restart. However, wifiManager.setTimeout(60) is not working at all. It get stuck and display these lines :

*WM: AutoConnect

*WM: Connecting as wifi client...

*WM: Using last saved values, should be faster

It never displays this :

"failed to connect and hit timeout"

which means wifiManager.setTimeout(60) is not working . Below is the code:

  #include <ESP8266WiFi.h>

 //needed for library
 #include <DNSServer.h>
 #include <ESP8266WebServer.h>
 #include <WiFiManager.h>

  void setup() {
       // put your setup code here, to run once:
       Serial.begin(115200);

      //WiFiManager
       //Local intialization. Once its business is done, there is no need to
       //keep it around
        WiFiManager wifiManager;
      //reset settings - for testing
      //wifiManager.resetSettings();

     //sets timeout until configuration portal gets turned off
     //useful to make it all retry or go to sleep
      //in seconds

      wifiManager.setTimeout(60);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
 //here  "AutoConnectAP"
 //and goes into a blocking loop awaiting configuration

  if(!wifiManager.autoConnect("AutoConnectAP")) {
     Serial.println("failed to connect and hit timeout");
     delay(3000);
     //reset and try again, or maybe put it to deep sleep
     //ESP.reset();
     ESP.restart();
     //ESP.deepSleep(20e6, WAKE_RFCAL);
    delay(5000);
   }

   //if you get here you have connected to the WiFi
   Serial.println("connected...yeey :)");

    ESP.deepSleep(20e6, WAKE_RFCAL);
    delay(3000);

 }

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

  }

I am using ESP8266 thing dev board. Can anyone please tell me what is wrong and how to resolve the issue ? Thank You!!

Try using setConfigPortalTimeout(60) instead of setTimeout(60)

Because it has been updated in version 0.10 of WiFiManager library.
see : https://github.com/tzapu/WiFiManager#010


DFROBOT I2C 16x2 Arduino LCD Display Module I2C communication interface What is the proper connection to the I2C communication interface (e.g., JST Jumper 4 Wire Assembly) of the DFROBOT I2C 16x2 Arduino LCD Display Module (SKU:DFR0063)? I wish to connect 4 wires assembly directly to it.

Here is schema how to connect it and example how to use it, also link to needed library. Hope this helps.

https://www.dfrobot.com/wiki/index.php/I2C/TWI_LCD1602_Module_(SKU:_DFR0063)

Anyway - I2C is prettty standardized interface, so googling any I2C schema for your type of Arduino will work as for connection - just connect SDA (A4) to SDA, SCL (A5) to SCL, GND to GND and VCC to VCC as writen on the module interface.

There are also lots of correct results for googling the module name - just google SKU:DFR0063 and you get many of correct links. On first page every second link contains link for the library, those others just refers to the manufacturer in text.


HUZZAH ESP-8266 (by ADAFRUIT): How to use with the ARDUINO R3 I have recently purchased a ESP-8266 HUZZAH by adafruit. I'm kind of new to the whole arduino concept. I would like to know how I would be able to utilise this breakout board with my Arduino to do anything. I have searched on the internet and I know about flashing the board. However, I have no idea how to flash this device. Some help would be appreciated.

I also have no idea where to put my pins. I know that there are RX and TX pins on the UNO, but those are at 0 and 1. Most online guides are using something like 11/12 or 2/3.

Here is the link to the product website

Thanks,
Vraj

Ok, I'll keep this post open for anyone who got this board and the Arduino and wanted to use them together (it's probably only me, but who cares). Anyway, when looking at this board it's basically it's own controller. The front pins are what you need to communicate with the board itself. It's meant to be used with a FTDI cable to the computer. Anyway, looking further into it we see many pins behind the first 6 or so. To connect it to the computer using the Arduino you need to use this config.

Arduino | HUZZAH ESP8266
RX | RX (In the front)
TX | TX (In the front)
5V | V+ (In the front)
GND | GND (In the front)

Also, you need to create a thing where the Arduino won't be able to function, making it a communicator port for the HUZZAH itself. To do this simply take one of the GND pins on the Arduino and connect it to the RESET pin on the Arduino. After doing this you need to set up your ESP8266. This is a link to a basic guide on how to do this by ADAFRUIT. Instead of the USB cable, you are using your arduino as a cable essentially (a pretty expensive one). Anyway, the port number should be the port that your arduino is connected to (to the computer). This is if you want to use the ARDUINO IDE.

To use NODEMCU LUA which it comes preloaded with, you need to refer to this guide.

The other thing I wanted to mention was how to utilise a basic board with the controller. I had to use a MFRC522 RFID board with the Arduino, and I wanted to send the info to the internet. Sadly, it seemed as if I couldn't use the arduino itself. To use this board I used many sources. First, was the library github (this one).

The next step was to get the pin layout (from here). However, if you look at it it's in the pin format of a WESMOS D1 MINI board. The final source was to look at the product page (here) and convert the pin format to fit the HUZZAH Board (It's in the PIN section). That took a long time, but now you're done. That's a basic guide on how I used the HUZZAH Board with my arduino.


error: 'analogRead' was not declared in this scope I am using Codeblocks with arduino IDE to simulate the control of a stepper motor, and the errors "'analogRead' was not declared in this scope" and "'A0' was not declared in this scope" keep popping. The code follows:

#include <Stepper.h>

const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0;  // number of steps the motor has taken

void setup() {
}

void loop()
{
    int sensorReading = analogRead(A0); //ERROR

    int motorSpeed = map(sensorReading, 0, 1023, 0, 100);

    if (motorSpeed > 0)
    {
        myStepper.setSpeed(motorSpeed);
        myStepper.step(stepsPerRevolution / 100);
    }
}

EDIT: Sorry I forgot to mention it clear, but I do not own a board, that's why I'm trying to simulate it on PC.

// yours code looks Ok, but i think problem is with Arduio IDE setting. Go to the "Tool > Boards...." in arduino IDE and make it sure that you have selected the right option of Arduino module. Mean it is same as you are using in hardware?


L298N, HC-05 Simple Bluetooth remote car not running in Arduino Arduino board type used in this session is Arduino Uno R3 DIP/SMD CH340

Below is the description of wiring and code in Arduino to assemble a Bluetooth RC car using android smartphone:

Tested the motor dc result both of wheel works (can spin forward and or backward). power direct from the battery.
Tested HC-05 bluetooth moduled. The phone can paired the bluetooth module.
Tested out1 out2 out3 and out4 on L298N using direct power from the battery the wheel spinning (forward and or backward).
The code for the Bluetooth rc simple car used below as described.

The car failed to move (forward, backward, turn left/right). how to make the motor dc and or the motor stepper works remotely. thank you

    #include
    SoftwareSerial mySerial(12, 13); // RX, TX
    #define m1 3
    #define m2 5
    #define m3 9
    #define m4 10

int data=0,kec=0;
boolean forward=true;

int fast[11]={0,80,100,120,140,160,180,200,220,240,255};

void setup()
{
  pinMode(m1,OUTPUT);
  pinMode(m2,OUTPUT);
  pinMode(m3,OUTPUT);
  pinMode(m4,OUTPUT);

  mySerial.begin(9600);
 }

void motorOut(unsigned char lpwm, unsigned char rpwm, boolean arrow){
   if(arrow==false){
      digitalWrite(m3,HIGH);
      digitalWrite(m1,LOW);
      analogWrite(m4,255-lpwm);
      analogWrite(m2,rpwm);
   }
   else{
     digitalWrite(m3,LOW);
     digitalWrite(m1,HIGH);
     analogWrite(m4,lpwm);
     analogWrite(m2,255-rpwm);
  }
}

void loop(){
  if(mySerial.available()>0){
    data=mySerial.read();
    if (data =='0') { kec=0;}
      else if (data =='1') { kec=1;}
        else if (data =='2') { kec=2;}
          else if (data =='3') { kec=3;}
            else if (data =='4') { kec=4;}
             else if (data =='5') { kec=5;}
              else if (data =='6') { kec=6;}
                else if (data =='7') { kec=7;}
                  else if (data =='8') { kec=8;}
                    else if (data =='9') { kec=9;}
                      else if (data =='q') {kec=10;}

  //S= Stop
 if (data == 'S')
 { motorOut(0,0,false); }

//F=Forward
if (data=='F')
{ motorOut(fast[kec],fast[kec],true); }

//I=turn right forward
if (data=='I')
{ motorOut(fast[kec],((fast[kec])/2),true);}

//G=turn left forward
if (data=='G')
{ motorOut(((fast[kec])/2),fast[kec],true); }

//R=turn right
if(data=='R')
{ motorOut(fast[kec],0,true); }

//L=turn left
if(data=='L')
{ motorOut(0,fast[kec],true); }

//B=back
if(data=='B')
{ motorOut(fast[kec],fast[kec],false); }

//H=turn left back
 if (data=='H')
   { motorOut(((fast[kec])/2),fast[kec],false); }

//turn right back
   if (data=='J')
    { motorOut(fast[kec],((fast[kec])/2),false); }
  }
}

sorry for my careless. finaly its works....wrong pin assign the main problem....should be IN1, IN2, IN4 and IN3 not IN1, IN2, IN3 and IN4. thank you for all hands for help before


Is supplying 5V from both external 5V and USB harmful? I have an arduino nano which is powered through unregulated 5V (pin 27). For debugging purpose, I'd like to connect the USB port to my computer in order to use the Serial.Print function. The external 5V will stay connected. Will this cause damage ?

edit : I forgot to mention that the external power supplied to pin 27 is regulated with a switching DC-DC converter (measured 5.1V). Sorry it was not clear in my question.

Here is my circuit :

The switching regulator is not exactly the one in the schema.

Is using the circuit with the battery power supply + usb connection to my computer will damage something ?

No, it probably won't damage anything, as the PC's USB port is protected from overvoltage by the D1 schottky device on your arduino board.

Update, my previous answer contained the following paragraph, which is not related to your problem

  But you should take care of some things.

  Make sure, the voltage applied to your +5V-Net is regulated properly elsewhere. I.e. choose a laboratory PSU or another good
  source.
  Avoid having both your PC and your 5V-supply connected to line voltage. Ground levels may differ due to Y-capacitors present in the
  switching PSUs. Those provide a AC voltage of half your line voltage
  to DC ground (only with 0.3 to 0.7 mA, but enough to cause
  disturbances on your signals at 55 volts in the US or 115 V in the EU)
  If you have to use two switching PSU for both PC and arduino, provide an equipotential bonding between your PC's mass (e.g.
  VGA-port-screw) to your arduino's PSU's ground directly, to prevent
  leakage currents from the Y-capacitors wandering around in your
  circuitry.

Update according to your enhanced question

You are using a battery powered DC-DC supply for your Arduino. So, my previous notes do not apply to your problem.

5.1 V seem exact enough to drive your arduino safely. No need for additional stabilisation measures
D1 (see genuine arduino schematic) separates USB-Power from +5V and prevents current flowing in reverse direction over your USB connection.
Arduino circuitry and USB port have common GND so there are always well defined voltage levels.

In my opinion, there's nothing with your setup, which may harm your circuitry or your PC.

Depending on the maximum power of your DC-DC converter you may consider adding a fuse to protect converter and components in case of short circuit.

Since the external 5V supply is not regulated, it may cause some problems. It is possible that a small voltage difference will appear if and when the external voltage fluctuates from the 5V level. What you should do is short-circuit the 5V of the USB to pin 27.

And in general, add a 5V regulator circuit to feed the Arduino nano, like this one:


Cannot upload sketch to Arduino Nano I've been using Arduino UNO for quite sometime and brought a new Arduino Nano. When I connected it to my computer, the power usb lit up and the blink sketch started running ( as expected of course).

Now I opened up the IDE and switched boards. But when I try to upload code to my Nano I get an error-

  avrdude: ser_open(): can't open device "\.\COM3": The system cannot find the file specified.

Clearly the IDE can't see my board. Uploading to my UNO goes fine. The serial port option is greyed out so I can't change it.

I have searched extensively online for a solution and have found none. This must be either a very unique issue or a very simple one.

When using a cheap knockoff Nano, it seems that in the newer versions of the Arduino IDE (at least in 1.8.8), you may need to select "ATmega328P (Old bootloader)" from the Processor options under the Tools menu in order to upload sketches.

I don't really see a question in the OP, but here is the immediate answer:

Go into Control Panel..Device manager.  Open the Ports (COM & LPT) and see what you have.  It should be listed.

If it is a CH340 port it will just give a COMx number.

If you have the genuine article then it will actually say so and give you the COMx number to use.

If no COM ports show then try switching out the cable.  Power cycle the Arduino and try again.

There aren't that many moving parts in this, but sometimes, Windows gets confused and a Windows reboot might be necessary.  That usually only happens if you unplug and replug the Arduino too many times for Windows to keep track of.


Bluetooth connection and RX ,TX I have connected a RN-42 bluetooth (TX-D0, RX-D1, VCC-5V, GND_GND) to arduino.The problem is that when I run this code ,nothing happens it just upload to infinite or it doesn't. I am checking with tera term. Is there a problem with the connection of the pins? Also when I pair my android phone to the bluetooth it says paired on the phone but the blue light of the bluetooth doesn't switch on, like it's not connected.

  #include <SoftwareSerial.h>// import the serial library
   SoftwareSerial Genotronex(1, 0); // TX,RX
   int ledpin=13; // led on D13 will show blink on / off
   int BluetoothData; // the data given from Computer

  void setup() {
  // put your setup code here, to run once:
   Genotronex.begin(9600);
   Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
   pinMode(ledpin,OUTPUT);
  }

  void loop() {
    // put your main code here, to run repeatedly:
  if (Genotronex.available()){
     BluetoothData=Genotronex.read();
   if(BluetoothData=='1'){   // if number 1 pressed ....
  digitalWrite(ledpin,1);
  Genotronex.println("LED  On D13 ON ! ");
   }
  if (BluetoothData=='0'){// if number 0 pressed ....
   digitalWrite(ledpin,0);
   Genotronex.println("LED  On D13 Off ! ");
   }
}
   delay(100);// prepare for next data ...
 }

As commenter by RSM

The issue you are facing is because you are using pins 0 and 1

These are used by the arduino for uart.

So for starters please use any pin other that 0 and 1.  But if you insist that you do need to use these pins,  then you don't need softwareserial you can use the default serial itself, but you will need to disconnect the bluetooth while programming.

Try taking off the bluetooth module, this will allow communication with
the computer, not the bluetooth module. I had the same problems with my
hc-06, and have not solved the ladder yet.


Connect bluetooth module when no pins free I need do communicate atmega88 with a smartphone via bluetooth using a bluetooth HC-05 module. The problem is that all my atmega pins are being used. Rxd and txd pins are being used by a keypad (Keypad at PORTD). My project is almost done, at this stage i don't want to change the micro. Is there any alternative to solve this problem? Thanks

The code you're using for the atmega88 should be almost directly compatible with an ATmega328P, I suggest you pick one of those up.

Also you can try to:

Multiplex pins:

http://users.ece.gatech.edu/~sudha/academic/class/ece2030/Lectures/blocks/examples-5.gif

OR

Use shift registers/IO expanders:

http://tronixstuff.com/2011/08/26/tutorial-maximising-your-arduinos-io-ports/

You can't magic more pins out of thin air.

There are basically two options open to you:

Don't use so many pins
Use a different MCU

You could move some functions off the main MCU and on to an external IO expander or shift registers, which means re-designing most of your project, or you could just use a bigger MCU which means only making comparatively minor changes to your project.


Is using malloc() and free() a really bad idea on Arduino? The use of malloc() and free() seems pretty rare in the Arduino world. It is used in pure AVR C much more often, but still with caution.

Is it a really bad idea to use malloc() and free() with Arduino?

My general rule for embedded systems is to only malloc() large buffers and only once, at the start of the program, e.g., in setup(). The trouble comes when you allocate and de-allocate memory. Over a long run session, memory becomes fragmented and eventually an allocation fails due to lack of a sufficiently large free area, even though the total free memory is more than adequate for the request.

(Historical perspective, skip if not interested): Depending on the loader implementation, the only advantage of run-time allocation vs. compile-time allocation (intialized globals) is the size of the hex file. When embedded systems were built with off the shelf computers having all volatile memory, the program was often uploaded to the embedded system from a network or an instrumentation computer and the upload time was sometimes an issue. Leaving out buffers full of zeros from the image could shorten the time considerably.)

If I need dynamic memory allocation in an embedded system, I generally malloc(), or preferably, statically allocate, a large pool and divide it into fixed-size buffers (or one pool each of small and large buffers, respectively) and do my own allocation/de-allocation from that pool. Then every request for any amount of memory up to the fixed buffer size is honored with one of those buffers. The calling function doesn't need to know whether it's larger than requested, and by avoiding splitting and re-combining blocks we solve fragmentation. Of course memory leaks can still occur if the program has allocate/de-allocate bugs.

No, but they must be used very carefully in regards to free()ing allocated memory.
I have never understood why people say direct memory management should be avoided as it implies a level of incompetence thats generally incompatible with software development.

Lets say your using your arduino to control a drone. Any error in any part of your code could potentially cause it to fall out of the sky and hurt someone or something. In other words, if someone lacks the competences to use malloc, they likely shouldn't be coding at all since there are so many other areas where small bugs can cause serious issues.

Are the bugs caused by malloc harder to track down and fix? Yes, but thats more of a matter of frustration on the coders part rather than risk. As far as risk goes, any part of your code can be equally or more risky than malloc if you don't take the steps to make sure it's done right.


Serial.write() prints a variable twice I have this code:

#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

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

char clat[11];
char clng[11];

void loop()
{

        bool isGpsLocationValid = false;
        do
        {
            while (ss.available()>0)
            {
                char c = byte(ss.read());
                if (gps.encode(c))
                {
                    if (gps.location.isValid())
                    {
                        dtostrf(gps.location.lat(), 11, 6, clat);
                        dtostrf(gps.location.lng(), 11, 6, clng);
                        isGpsLocationValid = true;
                    }
                }
             }
        } while (isGpsLocationValid == false);
        Serial.write(clat);
        Serial.println();
        Serial.write(clng);
}

Now when all is done, the clng value is printed twice in the serial monitor.
The value i get is in this format:

27.275869  15.151013
  15.151013

As you can see, clng is printed twice. Any ideas why is that?

The width parameter to dtostrf() is the width of the resulting string NOT including the null terminator. So you are overflowing the array.

Change:

char clat[11];
char clng[11];

to

char clat[12];
char clng[12];

and it should work.

OK, i found the problem. I guess this is an issue with the TinyGPS++ library.
When using gps.location.lat(), the output is 27.275869  15.151013, instead of just 27.275869.

So when also using gps.location.lng(), i get the double longitute....


arduino suddenly shows “avrdude: ser_open(): can't open device ”\\.\COM3" after last upload I am using arduino uno to make a sound detector. I uploaded a program, found error in the code that it returns unintended numbers unreasonably big. I also think I used wrong code for the module, but it was connected in the way that can work properly with the proper code.

The code I uploaded was:

const int ledPin =13;
const int middleValue = 512;
const int numberOfSamples =128;

int sample;
long signal;
long averageReading;

long runningAverage = 0;
const int averagedOver = 16;

const int threshold=400;

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

void loop(){
    long sumOfSquares = 0;
    for (int i=0; i<numberOfSamples; i++){
        sample = analogRead(0);
        signal = (sample - middleValue);
        signal *= signal;
        sumOfSquares += signal;
    }
    averageReading = sumOfSquares/numberOfSamples;
    runningAverage=(((averagedOver -1 )*runningAverage)+averageReading)/averagedOver;

    if(runningAverage>threshold){
        digitalWrite(ledPin, HIGH);
    }else{
        digitalWrite(ledPin, LOW);
    }
    Serial.println(runningAverage);
}

When the arduino suddenly stopped sending serial numbers, I pressed reset button and uploaded the default code:

void setup() {
}

void loop() {
}

but now it shows that it cannot connect to COM3 (arduino) and cant find the device, When I can see arduino uno successfully connected to PC using device manager (windows 8.1). The led light of arduino also turns on when I connect it to power source or usb.

it shows "port not found" when I click to see the serial output

Did I just fry Arduino? How should I fix this?

Also, i checked the led pin 13 blinking three times when i plug in the usb. I just cant upload anything

my arduino revived the next day.... don't know why but it works!


Can an AT89S52 be programmed using an Arduino as ISP? Since the AT89S52 controller is ISP programmable is it possible to use an Arduino UNO as a programmer to upload the hex file to the 8952 ?

I've tried various programmer softwares such as progisp, 8051 loader and ISP Prog v1.4 but the Arduino doesnt show up as a programmer on any of these. I've uploaded the ArduinoISP sketch on the UNO and then tried to program the 8952 without any luck.

According to my understanding the ISP programmers use an ATMega8 ,so is what I'm trying to do possible or do I need to purchace an ISP programmer ?

You should be able to use the Arduino as an ISP since an ISP is basically just a serial to SPI interface. If you are trying to use the arduino software to upload your program, you will need to edit your boards.txt file to be able to talk to the chip. If you are just using avrdude you will need to update your avrdude.conf.  AVR Freaks has a post on someone trying something similar and may be of some help. Without knowing your environment it's difficult to give more specific advice

If you haven't been successful yet, Try this.(assuming it's still not solved.)

I'm using Arduino to successfully program the AT89S52.
Need 2 tools:
Arduino program and
an AT89S52 programmer software.
Here's a complete tutorial on how to do it.
Works on Windows, not so sure about linux.
http://www.instructables.com/id/ARDUINO-AS-A-8051-PROGRAMMER/?ALLSTEPS


Standard Arduino kit button caps? Are there any caps available for these buttons, or am I better off using other, more stylish buttons if I want to make a presentable arduino-based gadget?

The circular hole drilled in their square-section moving part seems to suggest that something can be plugged there, but I can't seem to find caps anywhere.

Thanks for your attention.

You can use a different type of buttons on with your Arduino, there are some that keep the state or just push button.

The most used are the "arcade" style or the push button on a breadboard.

Just remember to have a pull up/down resistor and add some code to avoid debouncing when the button has been pressed.
https://www.arduino.cc/en/Tutorial/Debounce

If you want some more custom, you can use a normal push button and add small piece of wood/plastic/metal into the hole and having low friction you will be able to press the button with a nice look and feel.


How to handle multiple input pins at once? I am relatively new to Arduino platform and not know much. I am working on a Bicycle speedometer with turn and stop indicators.

I am planning on connecting an inductor magnet to calculate the rotation of my front wheel while providing the following services from the same arduino board:

Input horn and turn indicator switches.
Output to turn indicators.
Stop light when one of the brakes is
applied.

While I am sure of how to connect all the sensors, except the magnet, I am not sure how to handle the various inputs and the outputs at once.

I must be able to horn and stuff while the indicator blinks at a regular interval all the while the monitor keeps displaying my speed and distance covered.

Any reference or help would be greatly appreciated.
Thanks in advance.

Bharath. S.

How fast do we need to read the magnetic switch to not miss any pulses? I'll make some working assumptions:

Using 700c wheel and 28mm tire [assumed; adjust as necessary]
Rolling radius 2.1m [from here; there are other ways to arrive at this]
Max speed 22 m/sec (50mph), [working assumption; adjust as you see fit]
Magnet and switch interact for at most 3% of a rotation, [WAGuess]

The wheel will have to turn at ~10RPS at max speed giving a pulse period of 100ms. The pulse width will be at most 3% of that, or 3ms.

Your service loop would have to execute in somewhat less than 3ms, every time, in order to not miss any wheel pulses and that's if I haven't been too optimistic about the pulse width. I'd personally assume a 1ms maximum loop time, then test it on the road by sampling & logging wheel-pulse level with an Arduino at at least 10x that rate or 10+KHz.

Or I'd go with an interrupt-driven wheel pulse period timer not width) to ease the constraints on the main loop.

The main loop need only poll your turn, brake, and horn switches and a timer for blinking the turn signals. Even if the timing is a little erratic for some reason, no harm is done, and nothing is likely to be apparent to the rider or other road users.

Since your post mentioned that you are relatively new to Arduino, in case you have not done below, you may start by

a) get a printed book, ebook or 'well structured' tutorial, says, systematically covering 10 to 20 topics instead of short tutorial on just one topic

b) this will get you covered for your task 1 to 3, but, only as individual tasks.

c) after mastering (b), try to combine them, instead of stand alone in tutorial

d) interrupt is advance topic and not be cover in many starting books. You can see http://arduino.cc/en/Reference/attachInterrupt   Interrupt works only on certain pins, depending on which Arduino board model.


Using Arduino and Motor Shield I am a beginner in Arduino.I want to connect 2 motors to Arduino.
Do I require a motor shield?And if yes please tell why?
Also can i use an amplifier to increase the voltage for the motors?

And one last important question, I have just seen the motor shield's pic. Does it restrict arduino's pin usage? I mean we can't use the arduino pins if we use the motor shield right?

PS: I am talking about this model: SLAEX039 L293D Motor Shield

Thank a lot

Yes. To use standard D.C. motors, you must use a motor shield or the L239D chip. This is mainly due to motor noise, and control to run the motor at different speeds and directions. Also you get very easy to use libraries!


Using rotary encoders with pin change interrupts I'm using an Arduino Uno and two (3-pin) rotary encoders for a project. Since the loop takes a bit long and accuracy is important, I'd like to use interrupts to read the values from the rotary encoders. Also, pins 2 and 3 are occupied so I can't use hardware interrupts.

I'm using the Rotary library (github link) for the rotary encoders and the EnableInterrupt library (github link) for external interrupts. The Rotary library includes an interrupt example, but I couldn't manage to modify it to work with pin change interrupts. This is my current state (test code):

#include <EnableInterrupt.h>
#include <Rotary.h>

Rotary r = Rotary(2, 3);

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

  /* Original interrupt setup:
  PCICR |= (1 << PCIE2);
  PCMSK2 |= (1 << PCINT18) | (1 << PCINT19);
  sei();
  */

  enableInterrupt(2, interruptFunction, CHANGE);
  enableInterrupt(3, interruptFunction, CHANGE);
}

void loop() {

}

void interruptFunction() {

  Serial.println("Int. called");

  unsigned char result = r.process();
  if (result == DIR_NONE) {
    // do nothing
  }
  else if (result == DIR_CW) {
    Serial.println("ClockWise");
  }
  else if (result == DIR_CCW) {
    Serial.println("CounterClockWise");
  }
}

Everytime I turn the encoder for one step, the interruptFunction gets called a bunch of times (about 2~4) but the r.process() call never returns a value.

My current guess is that this has something to do with the rotary encoder outputting gray code, but I'm not quite sure how my approach differs from the Rotary interrupt example using hardware interrupts.

Hope you can help!

check the library to see if it debounces the input.

if not, write your own code. usually state machine-based approaches are very resistant to switch bounces.

The correct solution is to use a debouncing circuit. The MC14490 is a hex debouncing circuit and is perfect for this type of application. No need to block interrupts or set timers. It's available as either SMD or thru hole.


Which board's bootloader is on the microcontroller? Currently I'm doing a project that needs an Atmega2560 standalone MCU. After I burned the bootloader with this method: http://www.gammon.com.au/bootloader . I set the Board as "Arduino/Genuino Mega or Mega 2560" and the Processor as "ATmega2560 (Mega 2560)". But, it just stuck at "uploading" and this message pop up: "avrdude: stk500v2_ReceiveMessage(): timeout". So, I'm guessing I'm choosing a wrong board. Is there a way to check which board to select in the Tool tab?

It depends on which bootloader you loaded, when you write your bootloader with AVRDude you specify the hex file, Which Hex file did you specify?


Getting errors i don't understand I was following a tutorial for my class (the tutorial was assigned) and I did everything the guy did to the letter but i got errors he didn't and they were errors I didn't get while programing similar things with the exact same commands as what im getting errors on now.
Code
#include "DHT.h"
#define Type DHT11
#include <LiquidCrystal.h>
int rs=7;
int en=8;
int d4=9;
int d5=10;
int d6=11;
int d7=12
LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
int sensePin=2;
DHT HT(sensePin,Type);
float humidity;
float tempC;
float tempF;
int setTime=500;
int dt=1000;

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   HT.begin();
   delay(setTime);
   lcd.begin(16,2);
}

void loop() {
   humidity=HT.readHumidity();
   tempC=HT.readTemperature();
   tempF=HT.readTemperature(true);

   lcd.setCursor(0,0);
   lcd.print("Temp F= ");
   lcd.print(tempF);
   lcd.setCursor(0,1);
   lcd.print("Humidity= ");
   lcd.print(humidity);
   lcd.print(" %");
   delay(500);
   lcd.clear();

   Serial.print("Humidity: ");
   Serial.print(humidity);
   Serial.print("% Temperature ");
   Serial.print(tempC);
   Serial.print(" C ");
   Serial.print(tempF);
   Serial.print(" F ");
}

Error message
Arduino: 1.8.13 (Windows 10), Board: "Arduino Uno"

DHT_LCD_lab:10:2: error: expected ',' or ';' before 'LiquidCrystal'
  LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
  ^~~~~~~~~~~~~
C:\Users\zacha\Desktop\DHT_LCD_lab\DHT_LCD_lab.ino: In function 'void setup()':
DHT_LCD_lab:24:1: error: 'lcd' was not declared in this scope
 lcd.begin(16,2);
 ^~~
C:\Users\zacha\Desktop\DHT_LCD_lab\DHT_LCD_lab.ino: In function 'void loop()':
DHT_LCD_lab:34:1: error: 'lcd' was not declared in this scope
 lcd.setCursor(0,0);
 ^~~
exit status 1
expected ',' or ';' before 'LiquidCrystal'

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

#include "DHT.h"
#define Type DHT11
#include <LiquidCrystal.h>
int rs=7;
int en=8;
int d4=9;
int d5=10;
int d6=11;
int d7=12;
LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
int sensePin=2;
DHT HT(sensePin,Type);
float humidity;
float tempC;
float tempF;
int setTime=500;
int dt=1000;

void setup() {
  // put your setup code here, to run once:
   Serial.begin(9600);
   HT.begin();
   delay(setTime);
   lcd.begin(16,2);
 }

void loop() {
   humidity=HT.readHumidity();
   tempC=HT.readTemperature();
   tempF=HT.readTemperature(true);

   lcd.setCursor(0,0);
   lcd.print("Temp F= ");
   lcd.print(tempF);
   lcd.setCursor(0,1);
   lcd.print("Humidity= ");
   lcd.print(humidity);
   lcd.print(" %");
   delay(500);
   lcd.clear();

   Serial.print("Humidity: ");
   Serial.print(humidity);
   Serial.print("% Temperature ");
   Serial.print(tempC);
   Serial.print(" C ");
   Serial.print(tempF);
   Serial.print(" F ");
  }


Can't get 4 digit 7 segment display to show different values I'm an Arduino newbie having problems getting a 4 digit 7 segment display to work. The display is connected to a 74HC595 and the setup is from the elegoo tutorial 28 (I think it is download only).

I figured how to control which number to display, but all 4 digits always share the same number, so it is always like 1111, 5555, 9999 etc.

I've heard about something called multiplexing which might do the trick, but I can't adapt it to my project yet, missing too much experience.

This is the code that toggles between 2222 and 8888.
I want to be able to display any number like 1234 though.

Any help is very appreciated.

int latch=9;  //74HC595  pin 9 STCP
int clock=10; //74HC595  pin 10 SHCP
int data=8;   //74HC595  pin 8 DS

void setup()
{
  pinMode(latch,OUTPUT);
  pinMode(clock,OUTPUT);
  pinMode(data,OUTPUT);
}

void Display(unsigned int num)
{
  digitalWrite(latch,LOW);
  shiftOut(data,clock,MSBFIRST,num);
  digitalWrite(latch,HIGH);
}

void loop()
{
    Display(91);
    delay(1000);
    Display(127);
    delay(1000);
}

You have a common cathode display and all your cathodes are tied to ground through resistors. You have no way at all of separating out the different digits.

You cannot directly drive such a display with a shift register like that - you need a more direct connection to the Arduino (it needs to be high speed) and rapidly switch each cathode on and off in sequence to display each of the four numbers one after another.

Also the resistors should be in the 8 anodes, not the 4 cathodes.

That circuit needs a 0.1uF cap from '595 VCC to Gnd for consistent operation. Ideally a resistor between each '595 output and the anode pin, and a transistor or other higher current device able to sink the current from 8 anodes being driven at once (i.e. ULN2003).  Once the cathodes can be driven seperately, to allow each digit to be selected individually, than an array can be used to map the digit to be displayed to the segments in a display:

// add before setup()
byte fontArray[] = {
0b00111111, // 0  where the bits represent dp-g-f-e-d-c-b-a
0b00000110, // 1  and 1 = segment turned on
0b01011011, // 2
// etc.
};

// and change this line in display() to display a number

shiftOut(data,clock,MSBFIRST,fontArray[num); // looks up mapping from above

// then turn on a cathode to display it for 2-3mS, then back off, and send
// out the info for the next digit


Why do I get avrdude: stk500v2_ReceiveMessage(): timeout error when uploading to Arduino Mega? I have an Arduino Mega clone and I haven't used it for a while. I remember it not working so when I plugged it in and tried uploading the code to it and sure enough it didn't work. So I plugged in an Uno and it worked. The Mega is a 2560 Atmel. Here's my code:

#define distanceForward A0
#define distanceLeft A1
#define distanceRight A2
#define distanceRightAngle A3
#define distanceLeftAngle A4
#define distanceBack A5
int talk = 2;

void setup() {
  Serial.begin(9600);
  pinMode(talk, OUTPUT);
  pinMode(distanceForward, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Front Facing
  pinMode(distanceLeftAngle, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Left Angle
  pinMode(distanceRightAngle, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Right Angle
  pinMode(distanceLeft, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Left
  pinMode(distanceRight, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Right
  pinMode(distanceBack, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, back
}

void hall_roam() {
  Serial.write("forward");
  if (analogRead(distanceLeftAngle) < 30) {
    Serial.write("right");
    if (analogRead(distanceLeftAngle) > 30) {
      Serial.write("forward");
    }
    if (analogRead(distanceRightAngle) < 30) {
      Serial.write("left");
      if (analogRead(distanceRightAngle) < 30) {
        Serial.write("forward");
      }
      if (analogRead(distanceForward) < 60) {
        Serial.write("stop");
        if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
          Serial.write("left");
          if (analogRead(distanceForward) > 60) {
            Serial.write("stop");
          }
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) > 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) > 60)) {
        Serial.write("right");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      } else {
        Serial.write("forward");
      }
    }
  }
}

void roam() {
  Serial.write("forward");
  if (analogRead(distanceForward) < 60) {
    Serial.write("stop");
    Serial.write("left");
    if (analogRead(distanceForward) > 60) {
      Serial.write("stop");
      Serial.write("forward");
    }
  }
}

void talkbb8() {
  pinMode(talk, HIGH);
  pinMode(talk, LOW);
}

void chill() {
  Serial.write("stop");
  talkbb8();
}

void loop() {
  if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
    hall_roam();
  } else if ((analogRead(distanceForward) < 60) && (analogRead(distanceBack) < 60)) {
    Serial.write("left");
    if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
      Serial.write("stop");
      hall_roam();
    }
  } else {
    roam();
  }
}

If there's a bracket out of place or something it's probably nothing. I'm talking about the characters. Is there anything in the characters that would screw up the upload like the three "!!!" problem I heard about or something like that. It's possible that the USB chip in it isn't recognized by my iMac. If so how do I fix that?

The error message basically means that the programmer is unable to contact the boot-loader on the device. The code you're trying to upload has no bearing on the problem.

There could be one of the four possible reason behind it. They are:

Wrong Port Selected:

If TX/RX led is not blinking, then you may have selected wrong port. If one of both of them are blinking then, you aren't using the wrong port. It might be worth checking again though, sometimes USB COM devices install on strange port numbers.
Board is not in Bootloader Mode:

The Arduino Mega is not executing the bootloader for some reason. If the programmer is not resetting the micro before attempting to connect, this might be the reason. Try to reset the board (press and release the button) while the programmer is attempting to connect. Sometimes software that runs in a tight loop will prevent the bootloader from connecting.
Barring that, the fuses might have gotten messed up or the code erased. You would need to reflash the bootloader and proper fuses, again, see the appropriate info page for your device.
Arduino Mega 2560 only: ATmega8U/16U software

Might not be working and would need reprogramming. See the Programming section on the info page, you will need the firmware and Atmel-compatible DFU (device firmware update) software on your computer toreflash the target.
Hardware damage:

There could be hardware damage to the board, AVR(s), or FTDI chip. Time to buy another board.

You can check this answer.

If you have a timeout issue please ensure the crystal used on board is 16 Mhz.

change

mega.menu.cpu.atmega2560.upload.protocol=wiring

To:

mega.menu.cpu.atmega2560.upload.protocol=stk500v2

I had this problem after changing crystal value and changing parameters solved the above problem.


prgramming arduino led on then off i want the led to light at the beginning and stays like this for a while then turns off, so i wrote:

int led=13;
void setup() {
  pinMode(led,OUTPUT);
}
void loop() {
    digitalWrite(led,HIGH);
    delay (5000);
    digitalWrite (led,LOW);
}

as i understand it should start with high means on digitalWrite(led,HIGH)...and stays like this for 5000us  delay (5000)  then it should turn off with  digitalWrite (led,LOW).
but why its not working, it starts with off for afew seconds then stays on..what i understand wrong with these simple steps ????

It immediately loops, from the digital write low to digital write high. Add a second delay after the low, so that it waits before it loops to the top again.

That delay does not do anything but wasting 5 seconds...you need to do like:

void loop() {
    digitalWrite(led,HIGH);
    delay (2500);
    digitalWrite (led,LOW);
    delay (2500);
}

The code runs sequentially...in your code after turning off the led it immediately turns it on again and waits 5 seconds...this is so fat that you do not notice it.