text:
CC3000 cannot sending post data with content length more than 104
I'm trying to post data from my Arduino due to my web server (php) through POST using the CC3000 breakout board and for some reason, data with content length more than 104 is not being sent?
I've tried posting directly with postmaster with content length value greater than 104 to verify that it wasn't my server denying the request and it wasn't. So something with the Arduino or cc3000?
Right now, my post request looks like this which works:
POST /new/path/post.php HTTP/1.1
Host:  www.mywebsite.com
User-Agent: Arduino/1.0
Connection: close
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 104

userId=32&sscId=43&raVal=52&cvVal=62&bbvfgTempInF=723&bbvfgLevel=82345&humidity=92&lmassLevel=0283838383

And this is the one that doesn't (notice only one character difference in userId):
POST /new/path/post.php HTTP/1.1
Host:  www.mywebsite.com
User-Agent: Arduino/1.0
Connection: close
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 105

userId=322&sscId=43&raVal=52&cvVal=62&bbvfgTempInF=723&bbvfgLevel=82345&humidity=92&lmassLevel=0283838383

And here is my full code:
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include "utility/debug.h"

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   28  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  26
#define ADAFRUIT_CC3000_CS    22
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                                         SPI_CLOCK_DIVIDER); // you can change this clock speed

#define WLAN_SSID       "mynetwork"   // cannot be longer than 32 characters!
#define WLAN_PASS       "mypassword"
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

#define IDLE_TIMEOUT_MS  10000      // Amount of time to wait (in milliseconds) with no data
                                   // received before closing the connection.  If you know the server
                                   // you're accessing is quick to respond, you can reduce this value.

/**************************************************************************/
/*!
    @brief  Sets up the HW and the CC3000 module (called automatically
            on startup)
*/
/**************************************************************************/

uint32_t ip;

void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

  /* Initialise the module */
  Serial.println(F("\nInitializing..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }

  // Optional SSID scan
  // listSSIDResults();

  Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /* Display the IP address DNS, Gateway, etc. */
  while (! displayConnectionDetails()) {
    delay(1000);
  }

  ip = 0;
  // Try looking up the website's IP address
  Serial.print(WEBSITE); Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(WEBSITE, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }

  cc3000.printIPdotsRev(ip);

  // Optional: Do a ping test on the website
  /*
  Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip); Serial.print("...");
  replies = cc3000.ping(ip, 5);
  Serial.print(replies); Serial.println(F(" replies"));
  */

  /* Try connecting to the website.
     Note: HTTP/1.1 protocol is used to keep the server from closing the connection before all data is read.
  */
  Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
  if (www.connected()) {
    Serial.println("Connected");
    String PostDatat = "userId=32&sscId=43&raVal=52&cvVal=62&bbvfgTempInF=723&bbvfgLevel=82345&humidity=92&lmassLevel=0283838383";

    Serial.println();
    Serial.println("POST /new/path/post.php HTTP/1.1");
    Serial.println("Host: www.mywebsite.com");
    Serial.println("User-Agent: Arduino/1.0");
    Serial.println("Connection: close");
    Serial.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
    Serial.print("Content-Length: ");
    Serial.println(PostDatat.length());
    Serial.println();
    Serial.println(PostDatat);

    //HANGS HERE IF CONTENT LENGTH > 104

    www.println("POST /new/path/post.php HTTP/1.1");
    www.println("Host: www.mywebsite.com");
    www.println("User-Agent: Arduino/1.0");
    www.println("Connection: close");
    www.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
    www.print("Content-Length: ");
    www.println(PostDatat.length());
    www.println();
    www.println(PostDatat);

    Serial.println();
    Serial.println("POST /new/path/post.php HTTP/1.1");
    Serial.println("Host:  www.mywebsite.com");
    Serial.println("User-Agent: Arduino/1.0");
    Serial.println("Connection: close");
    Serial.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
    Serial.print("Content-Length: ");
    Serial.println(PostDatat.length());
    Serial.println();
    Serial.println(PostDatat);

    Serial.println("SENT");
  } else {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("-------------------------------------"));

  /* Read data until either the connection is closed, or the idle timeout is reached. */
  unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    while (www.available()) {
      char c = www.read();
      Serial.print(c);
      lastRead = millis();
    }
  }
  www.close();
  Serial.println(F("-------------------------------------"));

  /* You need to make sure to clean up after yourself or the CC3000 can freak out */
  /* the next time your try to connect ... */
  Serial.println(F("\n\nDisconnecting"));
  cc3000.disconnect();

}

void loop(void)
{
 delay(1000);
}

/**************************************************************************/
/*!
    @brief  Begins an SSID scan and prints out all the visible networks
*/
/**************************************************************************/

void listSSIDResults(void)
{
  uint32_t index;
  uint8_t valid, rssi, sec;
  char ssidname[33];

  if (!cc3000.startSSIDscan(&index)) {
    Serial.println(F("SSID scan failed!"));
    return;
  }

  Serial.print(F("Networks found: ")); Serial.println(index);
  Serial.println(F("================================================"));

  while (index) {
    index--;

    valid = cc3000.getNextSSID(&rssi, &sec, ssidname);

    Serial.print(F("SSID Name    : ")); Serial.print(ssidname);
    Serial.println();
    Serial.print(F("RSSI         : "));
    Serial.println(rssi);
    Serial.print(F("Security Mode: "));
    Serial.println(sec);
    Serial.println();
  }
  Serial.println(F("================================================"));

  cc3000.stopSSIDscan();
}

/**************************************************************************/
/*!
    @brief  Tries to read the IP address and other connection details
*/
/**************************************************************************/
bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

  if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

So after running this code and changing the PostDatat variable to the two data being 104 char long and 105 char long, the 104 char long goes all the way through and prints the message SENT to the Serial monitor. But the 105 char long just hangs after the first Serial.println() blocks and before the "www.println(..." Has anyone had or encountered this problem or can suggest a solution to this? Thanks!

I've gone through the library to locate the buffer where data is stored before being transmitted and I noticed that the minimum TX buffer size is set to 130 bytes. Certain control information in the form of headers are sent along with your data to the CC3000. The CC3000 interprets these headers, strips them away and re-formats your data for transmission to your gateway. So when your 105-byte content was added to these headers, the whole packet exceeded the 130-byte buffer and so caused it to overflow, overwrite a 'magic number' at its end, that is meant to detect this condition, and cause the program to stall indefinitely; this is all by design. From ccspi.h:
// The magic number that resides at the end of the TX/RX buffer (1 byte after the allocated size)
// for the purpose of detection of the overrun. The location of the memory where the magic number
// resides shall never be written. In case it is written - the overrun occured and either recevie function
// or send function will stuck forever.
#define CC3000_BUFFER_MAGIC_NUMBER (0xDE)

The value of the number itself doesnt matter; its presence/absence is what is important. So this is where your code most likely got stuck:
/* The magic number that resides at the end of the TX/RX buffer (1 byte after the allocated size)
   * for the purpose of overrun detection. If the magic number is overwritten - buffer overrun
   * occurred - and we will be stuck here forever! */
  if (wlan_tx_buffer[CC3000_TX_BUFFER_SIZE - 1] != CC3000_BUFFER_MAGIC_NUMBER)
  {
    DEBUGPRINT_F("\tCC3000: Error - No magic number found in SpiWrite\n\r");
    while (1);  //Infinite loop; end of the road
  }

And the reason you didnt get this error message is because debug mode is disabled by default in the library. You can enable it by changing #define DEBUG_MODE (0) to #define DEBUG_MODE  (1) in debug.h in the utility folder in the library.
Note that this buffer limitation applies to incoming data, as well as outgoing data.
Now you can increase the buffer size by changing:
#define CC3000_MINIMAL_TX_SIZE      (130 + 1)

to:
#define CC3000_MINIMAL_TX_SIZE      (150 + 1) // buffer size is now 150 bytes

in cc3000_common.h in the utility folder in your library folder, save the file and try again.
Even if this works though, I suggest you choose a fixed chunk size for sending data, one that is reasonably below 130 bytes. What happens next time when you want to send a 200-byte string? You increase the buffer again and you deprive the rest of your sketch of valuable SRAM. What you do is pass your POST content to some function that splits the string into chunks and sends them one at a time.
Assuming you send only ASCII strings:
#define CHUNK_SZ  80  // your chunk size

void send_all(Adafruit_CC3000_Client * conn, const uint8_t * data, uint16_t len){
  while (len >= CHUNK_SZ){   // while the length is greater than your chunk size
    conn->write(data, CHUNK_SZ);  // write a chunk to the socket
    data += CHUNK_SZ;  // advance the pointer to the start of the next chunk
    len -= CHUNK_SZ;  // get how many bytes are left
  }
  if (len)  // send whatever remains if anything remains
    conn->write(data, len);
}

void loop(){
  ...

  Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
  const uint8_t[] PostDatat = "userId=32&sscId=43&raVal=52\r\n";
  send_all(&www, PostDatat, sizeof(PostDatat) - 1); // -1 is to ignore the null byte

  ...
}

The function takes a pointer to your CC3000 socket object, a pointer to your data and the size of the data (array or not) in bytes. It should work for C strings. Note that I explicitly added \r\n at the end of the POST content, since println() isnt used here. I used the uint8_t type so that you can also use the function to send an arrays of ints or other numeric types, as long as you cast the array to uint8_t * and specify the length of the array in bytes with sizeof().
Finally, try to make your chunk size as large as you can without getting too close to the limit. A large chunk size means fewer chunks, which means less overhead (remember those pesky headers) and time taken to transmit your whole request.

Changed it and checked, but still the same issue :(

@dmantor try replacing all the www.println() and Serial.println() with www.println(F()) and Serial.println(F()). Use this only for string literals.

Also have you tried other lengths like 120, for instance? Why are you printing the POST to Serial twice?

I tried the replace to F() and still nothing. What does that do anyways? Also, I did try 120 and any length over 104 doesn't work :/ . And I have POST twice cause I wanted to see how the post looks before its sent even if it gets stuck at the actual POST. That was more for testing and seeing where my code was failing before.

@dmantor I've edited my answer

Changing the cc3000_common.h worked! Woo, thanks! Could you please just explain a little bit more on why the 105 failed when the limit was 130? Are there extra headers added on the content I assume that takes the other 25 more bytes by default? Also, I really don't want to change the library to make it work as a long term solution either...so could you please elaborate a little bit on the 50byte max chuck and an example of how to do that? Thanks! Much appreciated

@dmantor edited my answer again. glad it worked out for you.

Does it print out the part "Free Ram: " If not, then I doubt its a memory problem. Not too familiar with the CC3000, but possibly related to a UART Break Condition.

Was thinking the same thing before, but it did show. Regardless, the problem has been solved by @TisteAndii 's solution :D


text:
digitalPinToInterrupt() doesn't work

I am working on a protection circuit with 2 raindrop sensors which would be hooked onto the arduinos 2 interrupt pins and as soon as they detect water they shut some relays off, turn a red led on and exit() the main program.
These sensors I have order are working fine as regular input pins with the following code:
// lowest and highest sensor readings:
const int sensorMin = 0;     // sensor minimum
const int sensorMax = 1024;  // sensor maximum

void setup() {
  // initialize serial communication @ 9600 baud:
  Serial.begin(9600);
}
void loop() {
  // read the sensor on analog A0:
    int sensorReading = analogRead(A0);
  // map the sensor range (four options):
  // ex: 'long int map(long int, long int, long int, long int, long int)'
    int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

  // range value:
  switch (range) {
 case 0:    // Sensor getting wet
    Serial.println("Flood");
    break;
 case 1:    // Sensor getting wet
    Serial.println("Rain Warning");
    break;
 case 2:    // Sensor dry - To shut this up delete the " Serial.println("Not Raining"); " below.
    Serial.println("Not Raining");
    break;
  }
  delay(1);  // delay between reads
}

I will use the digital output not the analog but this doesn't change much. For the digital the pin is up at 5V at start and will be put to LOW once water is detected by the sensor.
I using the mega right now for breadbording but micro will be the final board.
Both the mega+micro should have 2,3 as interrupt pins:
Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21
Micro, Leonardo, other 32u4-based   0, 1, 2, 3, 7

I have modified the following code and tried all conditions:
LOW to trigger the interrupt whenever the pin is low,
CHANGE to trigger the interrupt whenever the pin changes value
RISING to trigger when the pin goes from low to high,
FALLING for when the pin goes from high to low.

It doesn't respond to any (the same time as I said the pin works fine as regular input).
Here in the setup I know that I am not using
attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE);

but
attachInterrupt(interruptPin, myISR, FALLING);

that is because the IDE doesn't recognize this function. Is there any problem with the code? If I understand interrupts correctly I don't even need to check for that if ( ISRRan ) to break off the while loop, once the interrupt comes in the ardu SHOULD be running my interrupt function and immediately run the protection code then abort.
byte interruptPin = 0;  // your interrupt pin
volatile boolean ISRRan = 0;  // this variable is set in your ISR to trigger a break in the while loop
byte C = 0;  // this is just the counter var for the while loop

void setup() {
 attachInterrupt(interruptPin, myISR, FALLING);
}

void myISR() {
 ISRRan = 1;
 // do other things in the ISR
}

void loop() {
 while ( C < 10 ) {
   if ( ISRRan ) {
     break;
   }
   //doing something inside the while loop
 C++;
 }
 // do other things outside of the while loop
 ISRRan = 0;  // Reset for whatever reason
}

Where your period definition ? Which hardware allow rapid communication ? C++ set a period, mean clock_time x count. You haven't any data when scanning counter on count. Use a lot delay for prepare device + communication. 9600 rate need minimal 0.3 second delay(mean 300 milisecond)(of course can use less delay value but lost a lot data !)

You could rework without interrupts. Rain doesn't exactly start and stop within a millisecond. Just test the sensor in your main loop.

https://www.arduino.cc/en/Reference/AttachInterrupt has some hints on mapping pins to interrupt numbers, if digitalPinToInterrupt(pin) doesn't work.

I have solved this.
The problem was with the pinout indeed.
attachInterrupt(0, myISR, FALLING);

will use the DIGITAL PIN 2
I was using attachInterrupt 2, that's all.

source: Stack Exchange

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

sort: votes


text:
How to reduce current from a AC TO DC power supply for arduino use
I have a AC to DC converter that was originally used for recharging the PSP, I stripped the 2 wires of the output and was wanting to use it for my arduino instead of using a 9V battery, it's output is 5V 2000MA, is there a way to reduce the current in order to use it for the arduino and im guessing the 5V is enough to power it...right? Im kinda new to electronics and the arduino so any help is much appreciated :D.
Thanks,
Liam.

See this question on EE.SE, it should clear up some of your confusion.

You don't need to reduce the current.
2000MA (2 amps) means the power supply is CAPABLE of supplying this (without overheating). Anything less than this, and your device will work perfectly.
Your Arduino will DRAW a certain number of milliamps (amps), this is the amount of current that will ACTUALLY run through your circuit.

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


text:
Can't make my stepper motor run clockwise and counterclockwise with AccelStepper Library
I'm relatively new to arduino thus need your help to figure out why my stepper motor doesn't rotate clockwise and counterclockwise. All I could do was to make it rotate only in one direction.
Here is my code:
#include <AccelStepper.h>

int pos=16000;
AccelStepper stepper(1,4,5);

void setup() {
stepper.moveTo(pos);
stepper.setMaxSpeed(6400);
stepper.setSpeed(6400);
}

void loop() {
if (stepper.distanceToGo() == 0)
{
  stepper.setCurrentPosition(0);
  pos = -pos;
  stepper.moveTo(pos);
  stepper.setSpeed(6400);
}
   stepper.runSpeed();
}

Will appreciate any help you can give me :)

The  “Performance” paragraph of the “Detailed Description” section of AccelStepper documentation says:

The fastest motor speed that can be reliably supported is about 4000 steps per second at a clock frequency of 16 MHz on Arduino such as Uno etc. ...

and the AccelStepper::setSpeed () documentation says:

... Speeds of more than 1000 steps per second are unreliable

Try changing your 6400-steps-per-second setting to a some plausible number, eg 500 or 1000.
Actually, it would make sense to start out with moderate destination settings and speeds, like a target position of 200 instead of 16000, and steps-per-second of 100, or whatever count it takes for say exactly two shaft revolutions.  Once you have that working right, then start doubling numbers until it no longer works, after which you can back off by a factor of say four (to allow for variations in load, etc).

Thxs, I'll try to lower a speed

Actually after trying different options, I could finally find a solution that seems to work for me:
if (stepper.distanceToGo() == 0 && stepper.currentPosition()==50000) {
    delay(1000);
    stepper.setCurrentPosition(0);
    stepper.moveTo(-50000);
    stepper.setSpeed(10000);
    stepper.runSpeedToPosition();
  }
  else if (stepper.distanceToGo() == 0 && stepper.currentPosition()==-50000) {
    delay(1000);
    stepper.setCurrentPosition(0);
    stepper.moveTo(50000);
    stepper.setSpeed(10000);
    stepper.runSpeedToPosition();
  }
  stepper.runSpeed();

Just out of interest, you are still using a speed which is an order of magnitude greater than 1000, which as jwpat points out is unreliable. What happened when you used speeds of <1000? Did it not work?

Yes, I'm still using high speeds, but I guess it works for me because my stepper motor is configured on a micro step. If I put a speed lower than 1000 it also works, but very slowly


text:
5V Trinket only outputting 3.3V?
Unless my multimeter is on the fritz, it would seem my 5V Adafruit Trinket is only outputting 3.3V when connected w/ DC power.
When connected via USB, totally fun. Full 5V. But if I disconnect that and connect a 9V wall adapter, the output of the 5V pinout is just giving me 3.3V.
Is that even possible?
I noticed the issue b/c my program wasn't running properly when connected via the DC adapter (but ran just fine via USB). So I tested the voltage and sure enough, 3.3V all around at basically every +/- connection.
Any ideas?

Can you measure the 9V input at the jack? Is it really 9V?

@NickGammon Yes, and it is indeed reading 9V.

I can't see from your photos where the 9V input actually gets onto the Trinket. Maybe the camera angle is a bit weird.

@NickGammon in the bottom photo if you follow the red/black, they go to the first and second inputs immediately to the top left of the trinket.

I'd prefer a photo that proved that point. Anyway, measure on the Trinket what it says between Bat+ and Gnd.

Also please photograph the underneath of the board.

The 5 things along the bottom of the last photo look light lights of some kind? What sort of lights are they? And what is the rating on the power supply (output, in milliamps or amps)?

If it's a steady 3.3V it's likely they've soldered the wrong regulator on it (or shipped you the 3.3V version). If your peripherals draw too much power, your voltage could also drop.

Unfortunately I do not have the ability to comment. What I can suggest is to look at the small 5 pin regulator and look at its markings. If the IC is marked with "QT33" then adafruit has stupidly soldered the wrong chip onto your trinket board. If it says "QT50" then the regulator is not at fault.


text:
master slave control of 2wd robots using xbee
Hi there I just need to ask you how I can send command from master robot to slave to follow using XBee. I have configured both the XBee in AT mode, but I totally don't have the clue how the program.
I am using the following kit components (from DF ROBOT) to build this project,

Romeo V2-All in one Controller (Arduino based controller).
Differential drive chasis with caster ball.
Wheel Encoders.
XBee 2mW PCB Antenna - Series 2 (ZigBee Mesh)  Transceiver module for the communication between two robots.
IR sensors.

6.Micro DC Geared Motor w/ Back Shaft (180rpm 6V).
I have done the programming for obstacle detection, positioning of robot, but I have no idea how to do the master slave programming logic.
Please help me on this. Here attached the code I have done till now:

const int InfraredSensorPin1 = 6;//Connect the signal pin to the digital pin 6
int detected2;
int detected1;
const int InfraredSensorPin2 = 9 ;

int E1 = 5;     //M1 Speed Control
int E2 = 6;     //M2 Speed Control
int M1 = 4;    //M1 Direction Control
int M2 = 7;    //M1 Direction Control

#define LEFT 0
#define RIGHT 1
int value;
long coder[2] = {
  0, 0
};
int lastSpeed[2] = {
  0, 0
};

void stop(void)                    //Stop
{
  digitalWrite(E1, 0);
  digitalWrite(M1, LOW);
  digitalWrite(E2, 0);
  digitalWrite(M2, LOW);
}
void advance(char a, char b)         //Move forward
{
  analogWrite (E1, a);
  digitalWrite(M1, HIGH);
  analogWrite (E2, b);
  digitalWrite(M2, HIGH);
}
void back_off (char a, char b)         //Move backward
{
  analogWrite (E1, a);
  digitalWrite(M1, LOW);
  analogWrite (E2, b);
  digitalWrite(M2, LOW);
}
void turn_L (char a, char b)            //Turn Left
{
  analogWrite (E1, a);
  digitalWrite(M1, LOW);
  analogWrite (E2, b);
  digitalWrite(M2, HIGH);
}
void turn_R (char a, char b)            //Turn Right
{
  analogWrite (E1, a);
  digitalWrite(M1, HIGH);
  analogWrite (E2, b);
  digitalWrite(M2, LOW);
}

void setup(void)
{ Serial.println("Start!");

 pinMode(InfraredSensorPin1, INPUT);
 pinMode(InfraredSensorPin2, INPUT);

advance(200,200);
  Serial.begin(19200);      //Set Baud Rate//
  attachInterrupt(LEFT, LwheelSpeed, CHANGE);    //init the interrupt mode for the digital pin 2
  attachInterrupt(RIGHT, RwheelSpeed, CHANGE);   //init the interrupt mode for the digital pin 3
}
void loop(void)
{
  if((InfraredSensorPin1==LOW&&!InfraredSensorPin2==LOW)||(InfraredSensorPin1==LOW&&InfraredSensorPin2==LOW))
  turn_L (100,100);

  else if ((InfraredSensorPin2==LOW&&!InfraredSensorPin1==LOW)||(InfraredSensorPin2==LOW&&InfraredSensorPin1==LOW))
  turn_R (100,100);

  else
  advance (80,80);
  static unsigned long timer = 0;                //print manager timer
  if (millis() - timer > 5) {
    Serial.print("Coder value: ");
    Serial.print(coder[LEFT]);
    Serial.print("[Left Wheel] ");
    Serial.print(coder[RIGHT]);
    Serial.println("[Right Wheel]");

    lastSpeed[LEFT] = coder[LEFT];   //record the latest speed value
    lastSpeed[RIGHT] = coder[RIGHT];
    coder[LEFT] = 0;                 //clear the data buffer
    coder[RIGHT] = 0;
    timer = millis();
  }
}
void LwheelSpeed()
{
  coder[LEFT] ++;  //count the left wheel encoder interrupts
}
void RwheelSpeed()
{
  coder[RIGHT] ++; //count the right wheel encoder interrupts
}

You can format your code with the {} button in the post editor.

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


text:
Is this bluetooth setup good?
I am trying to do this tutorial http://www.instructables.com/id/Chappie-Self-Balancing-Robot/  on building a self-balancing robot with uno. However, I bothered by the Bluetooth wiring. I've done Arduino projects with Bluetooth before and all the Hc-05 wirings I've seen have it connected to the Tx and Rx pins.Currently, I have my Bluetooth module wiring like this :   with http://cdn.instructables.com/FSK/AI30/HMMFE6UO/FSKAI30HMMFE6UO.MEDIUM.jpg.
Will the different wiring need a different implementation, the code I see on the chappie instructable link does not have any pin mentions but I'm not sure. Is the chappie wiring fine? should I change my wiring? should I change my code?
I'm confused.

Which code are you reading? At step 5 he wrote

Complete code can be found on the GITHUB.

The sketch file (here is the direct link) has the following lines:
const int rxpin = 11; // pin used to receive (not used in this version)
const int txpin = 4; // pin used to send to LCD

SoftwareSerial blue(rxpin, txpin); // new serial port on pins 2 and 3

This means that the bluetooth is using a software serial on pins 11 and 4.
I don't know where you got the image you posted, but anyway that wiring is not the same as the one in the instructable. With your wiring, you can either use the software serial on pins 0 and 1, or (better) use the hardware serial. To do so, remove or comment the lines I highlighted and then replace every call to blue with Serial.


text:
Can a 9V battery be used as a backup power supply (to Arduino Uno) while plugged directly into Vin and ground?
Sorry if this has been asked before, but I've read tons of threads and it seems the answer is only implied on a couple of occasions.
I'm an electrical noob, but I understand that a 9v battery plugged into a wall wort with a diode would serve as a battery backup if the power was cut from the wall wort.  I also understand that Vin on an arduino already has a diode to do this.
I'm currently powering a temp/humidity that is dumping data into MySQL using a standard A-B USB cable and 5V DC USB power supply.  I'd like to incorporate a 9V battery plugged into Vin and ground, so that if DC power turns off, I can dump the data onto the SD card instead (since my MySQL server may or not be running during an outage).

A few questions: 1) How much current does the board take when active? That helps size the battery. I doubt a standard 9V battery is large enough. 2) Is it acceptable for there to be a brief interruption? (eg. while switching supplies) 3) How long an outage are you planning for? Minutes? Hours? That helps size the backup battery.

Another question: Are you powering from USB for any reason? Except simplicity? If you powered from a wall-wart and put 12V into the power jack, then the simple solution of using a diode to Vin from a suitably-sized battery should work. (The battery would need to be 10V or less to allow for the diode voltage drops).

@Nick Gammon 1) I haven't tested this yet, but I'm sure it will be quite a bit.  The completed project will include the Uno, ethernet shield, sd card, and 2X16 LCD display.  2) A brief interruption (anything less than a few minutes should be fine) 3) Hours, most likely.  If an outage is more than a couple hours, the freezers will be emptied to reefer trucks.

@Nick Gammon  No, there's no reason I'm using USB.  I guess that's part of my question.  Is the 9V solution possible with the wall wart, because if so, I can use that.  I'm only powering off USB because that's what the uno usually comes with.  I'm not doing any data transfer with it or anything.

I doubt that the 9V battery will last hours. It might last long enough to send out a cry for help. Presumably one would be enough. But if the power goes off it might take a while for the temperature to drop enough to send an alert. You could try 6 x AA batteries - that would give you 9V and hopefully last a while. You could also test if the batteries are low with a voltage divider and an analog read. If the power goes, will you be able to use the Ethernet shield? Won't the router also be off?

Ah, right.  No, I wouldn't be able to use the shield, but that's where I would want to dump to SD.  I don't need the SD card unless the power is out and our server is down.  At that point, I could turn off the LCD and stop hooking up to the server.

I don't see how dumping to SD will save the frozen food. Anyway, with a larger battery at least it will keep going for a while.

Haha, definitely not food in the freezers!  It's adhesives/sealants that have shelf lives and need to be frozen or cooled.  We don't need to "save" them, but we need to know exactly what temp they're at at all times.  I guess my the only question left is, how do I determine what size diode I need going into Vin?

Probably any old "rectifier" diode rated for an amp or more. For example 1N4004 or similar. Once you get it all set up, make sure you test that things are happening the way you expect.

My problem with that is that the other side of the diode on the Arduino is normally powered up. So for example if you have a 12V supply in the power jack you'll have 11.3V at Vin (because of the diode drop). Thus you are pumping 11.3V into your 9V battery which won't be designed to handle it. It will probably get hot and explode.
You would need another diode specifically between the battery and Vin. And make sure that Vin is at least 10V so that the normal mains power does not charge the battery.
Bear in mind a 9V battery doesn't have much capacity. With the power LED on,  taking sensor readings, and sending data via Ethernet (if that is what you are doing) you may have only bought yourself 15 minutes.
I have a post about a temperature and humidity sensor which runs all the time from 3 x AA batteries. I think the batteries need replacing about every two years. The data is written to an SD card which you remove and plug into your computer when you want to.

when you have 9V hooked up to Vin and 5V coming in from the USB, it will use power from the 9V battery

Looks like I misread the question. @mwwalk is quite right. If you supply more than 6.6V through Vin then the circuitry switches the USB off. See here:

Vin is provided by the power jack (after a diode which drops it by 0.7V) - see blue ellipse. In any case (power jack or not) Vin goes through a voltage divider (two 10k resistors to the left of the red circle). This is compared to the output of the 3.3V voltage regulator. Therefore GATE_CMD is HIGH if Vin exceeds 6.6V. This turns off the MOSFET (green circle) and disconnects the USB power.

You're project looks pretty sweet, but unfortunately SD writing won't work for me.  I'm trying to develop a temp and humidity sensor that can be used for monitoring environmentally controlled rooms, areas, and freezers in a manufacturing facility.
I'm putting the data into MySQL so that current temp/humidity can be shown on large TVs live, as well as pulled up from anywhere in the shop via browser.

Well, you did say I can dump the data onto the SD card instead. I thought you were actively considering this.

No, when you have 9V hooked up to Vin and 5V coming in from the USB, it will use power from the 9V battery, not usb and the battery will quickly be depleted.

You are right. I misread the question as being about something plugged into the power jack.


text:
Can I turn a headset with a cord into a bluetooth headset with multiple connections?
I'd like to connect Arduino with bluetooth shield to multiple bluetooth devices (TV & baby monitor), plug a corded headset into the contraption, sprinkle LEDs on top, and do the following:
If there is a signal above certain threshold coming from the baby monitor listen to a mix of TV and baby monitor audio with LEDs blinking; otherwise listen only to TV audio.
Thus the questions:
Can bluetooth connect with multiple devices simultaneously?
What do I need to implement that?

AFAIK bluetooth does not support multiple connections, but I'm not really into BT4. As for BT2.0, you will need two bluetooth audio-enabled masters; connect them to the two sources and then you will have your audio signals and you can mix them or not. Arduino is not really needed if you can configure the modules from e.g. a pc. Anyway I don't know any BT2.0 audio master board. BT4 has profiles, but I don't know if you can take a general purpose BT4 board and get an audio stream from it...


text:
Arduino LDR sensor stained
I bought a light sensor (LDR), but he got stained, what it means? It is used? Or is residuum of time?
I must give back? I have to clean up or something?
I bought as new, so I tested one of the LEDs will not turn on.
I bought the (Mercado Livre in BRAZIL).
The product is:
http://www.gbkrobotics.com.br/exemplo-produto/p7-sensor-de-luz-com-leds.pdf
I pay R$8 BRL (equivalent aprox. $2 dollars) but, i just wanted to know if he had something I could do, because only shipping was R$ 13 BRL ($4 dollars)

I'm starting with Arduino, thx

Do you have a picture of the front, or a datasheet/part number?
It could be that the LED is in the wrong way around, or that it is simply broken.
The stains could be due to moist. Have you bought the item off e-bay? Then you should contact the seller, give him pictures of the stains and defective LED. They're usually very kind and if all else fails, you can open a PayPal dispute (if you really want to get your money back).

Hey, man! I update the question, please check?

I doesn't look that  bad in the photo. Try cleaning it with some alcohol or acetone on a tissue. Otherwise it's probably inconsistent thickness in the blue soldermask that was applied. This wouldn't affect it's function anyways.

It's a light sensor. So try covering the sensor (check if the lights go off) and try shining a flash-light on it. That might make all three LED's go on.

I've read you post a couple of times and I get the impression you would like this board to work, so here are some quick check to try and find the fault.

You need a bread board
An arduino
A 200-300 ohm resistor.
Some wires. About 6 hands :)

Connect the board ground to the breadboard.  Then connect the to the resistor.  Then connect that to the power supply ground.
Take the positive off the power supply and touch it to the LED1 pin and check LED1 lights up.  Repeat with 2 and 3.
Switch every thing off
Connect the Positive to the Vcc connection of the board.
Connect a wire between Arduino A0 and "Sinal Analog"
Load this sketch
   void setup() {
       Serial.begin(9600);
    }
   void loop() {
       Serial.println(analogRead(A0));
       delay(250);
   }

When you cover the LDR it should read a lower number when you shine a light on it should read a higher number.
Turn everything off again, and if you have a multi meter test the resistance of the resistor on the board it should be 300 ohms, but I can't remember which way to read the bands and it might be 10K ohms, which would be a problem.
If anything doesn't work then they can all be fixed for a few cents and you don't need to worry about the discolouration.
Hope that helps you.

Thank you for your help. The store sent me a new sensor. The LED3 dosn't work )):

If you don't need to return the broken one then replacing LED three should be very easy (if you get it the right way round) and then you have two :)


text:
How do I give the ENTER keypress?
I have a Teensy set up as a keyboard, joystick, and I'm giving keyboard commands. Letter and number keys are going fine. But when I try sending ENTER, I get some extra code in my Linux terminal:
$ 16424
16424: command not found

the code I have to give the ENTER key goes like this:
void setup() {
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  // read the digital inputs and set the buttons
  Joystick.button(1, digitalRead(0));
  Serial.println(digitalRead(0));
  if(digitalRead(0)==0){
    Keyboard.println(KEY_ENTER);
  }
  delay(50);
}

where is this  "16424" coming from, and how do I send an ENTER keypress?
I am using a Teensy 2.0, on Linux, with Arduino IDE 1.6.7.

Keyboard.println((char) KEY_ENTER); might be the problem?

You can't just "print" a key like that. You use print for sending text.
When you use println it sends an enter key along with your text, so you can do :
Keyboard.println("ls -al");

and it will send the text ls -al and press enter for you.
If you want to do it in the 'raw' way you will need to press and then release the key:
Keyboard.press(KEY_ENTER);
Keyboard.release(KEY_ENTER);


text:
Make LED blink using AVR assembly
I have an ATmega328P Arduino and am trying to make the LED blink using assembly without any additional includes. The goal is to have it blink for 1 second on, then 1 second off, however, it blinks incredibly quickly and is barely perceptible. Am I doing something incorrectly?
; DDRB       = 0x04
; PORTB      = 0x05
; TCCROB     = 0x25
; TCNT0      = 0x26
; 0b00000000 = OFF
; 0b00100000 = ON

setup:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x04, r16           ; Set DDRB to output
    out 0x05, r16           ; Set PORTB to ON
    ldi r16, 0b00000101     ; Set r16 with prescaler 1024 value
    out 0x25, r16           ; Set the TCCROB to 1024
    ldi r20, 0              ; Reset r20
    ldi r21, 1              ; Hold value 1 to increment r20
loop:
    in r17, 0x26            ; Read the timer
    cpi r17, 128            ; Check to see if the timer is halfway done (1/2 second, max 255 value)
    brbc 0, increment       ; If r17 <= 128 (max 255 val before resets to 0), invert current LED state
    rjmp loop
increment:
    adc r20, r21            ; Add r21 (1) to r20 (with carry)
    brbs 0, reset           ; If the carry branch is set, reset the register
    rjmp loop               ; Otherwise, run the clock
reset:
    ldi r20, 0              ; Reset the delay register
    cpi r16, 0b00000000     ; Check if r16 is set to LED OFF
    brbs 1, switchon        ; If it is, change it to ON
    ldi r16, 0b00000000     ; Otherwise, change it to OFF
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock
switchon:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock

It's part of my code. I thought that line should be there, but when it isn't commented, it doesn't blink, it remains solidly lit (as far as I can tell).

How long is your delay? It might be too small to see the LED blink.

“incredibly quickly”? It's so slow I can even see it blinking!

There is a bug with the logic of your program: once TCNT0 gets larger
than 128, it will continue to be larger than 128 for quite some time...
during which time you are continuously incrementing your r20 counter.
The simplest fix would be to reset TCNT0 right after the increment
label, with something like out TCNT0, zero_reg. Then you may want to
compare TCNT0 with 61 instead of 128, in order to get closer to the
desired blink frequency of 0.5 Hz.
Other than that, there are quite a few problems in the way you write
your code. jwpat7 has already pointed out some of them, and here are
more:

You should not increment a register with adc, but with plain add.
Both instructions update the carry bit, but adc also adds the
previous value of the carry bit to the target register.
Better yet, increment with inc, as it's purpose is more obvious. But
then you should test the zero bit, as inc does not update the carry
bit.
There is little point in resetting r20 once it has overflowed, as it
is zero at this point.

There are also quite a few ways the program could me made simpler. The
simplest would probably be to configure timer 1 to deliver an interrupt
every second, and toggle the LED in the ISR. If you do not want
interrupts, you can configure counter 1 in much the same way, only
without the “interrupt enable” bit, and check the interrupt flag in a
busy loop.
Below is a slightly simplified version of your program. I tried to keep
it as close as possible to yours, without using timer 1, nor interrupts,
and not even the interrupt flag. The code checks for timer 0 overflowing
by comparing its current value with the previous one.
.set PINB,     0x03
.set DDRB,     0x04
.set TCCR0B,   0x25
.set TCNT0,    0x26
.set LED_MASK, 0b00100000
.set PS_1024,  0b00000101

setup:
    ldi r16, PS_1024    ; Set r16 with prescaler 1024 value
    out TCCR0B, r16     ; Set the TCCROB to 1024
    ldi r16, LED_MASK   ; Set r16 to the LED bit
    out DDRB, r16       ; Set LED pin to output
    clr r18             ; Clear the saved timer
loop:
    ldi r20, 61         ; Initialize our software counter
check_timer:
    in r17, TCNT0       ; Read the timer
    cp r17, r18         ; Compare with previous value
    mov r18, r17        ; Save current value
    brsh check_timer    ; unless the timer has decreased, repeat
decrement:
    dec r20             ; decrement the software counter
    brne check_timer    ; if not zero, go back to checking the timer
toggle:
    out PINB, r16       ; toggle the LED
    rjmp loop

If we can use the timer overflow interrupt flag, then the test is
simpler, and we do not need to store the previous and current values of
the timer in registers:
check_timer:
    sbis TIFR0, TOV0    ; unless the timer has overflowed
    rjmp check_timer    ; check again for overflow
    sbi TIFR0, TOV0     ; otherwise clear the overflow flag

Thank you. I am new to assembly and the low-level mindset and this was very informative and helpful. The reason I didn't use more self-documenting instructions (like dec) is because I'm limited to an instruction subset as a challenge for an assignment.

Would you mind detailing a little bit more on why you use the value 61 exactly?

@JosueEspinosa: The Uno is clocked at F_CPU = 16 MHz. The timer ticks at F_T0 = F_CPU/1024. It overflows with a frequency F_TOV0 = F_T0/256. You want the toggling of the LED to happen at 1 Hz ≈ F_TOV0/61.

Just to clarify what out PINB, r16 does,  Atmel datasheets say "Writing a logic one to PINxn toggles the value of PORTxn, independent of the value of DDRxn."

It appears that your intent is to set TCCROB up with a 1024x prescale, and each time it counts up to 128, increment r20, and toggle the LED each time r20 overflows to zero.
That sequence ought to take 1024/16M · 128 · 256 seconds, or about 2.1 seconds, a fairly leisurely toggle rate.  If instead it's flashing a hundred or more times too fast, probably one of the comparisons is backwards.
Some of the following items might make it easier to debug the problem:
• Instead of brbc 0,..., say brcc ...
• Instead of brbs 0,..., say brcs ...
• Instead of brbs 1,..., say breq ...
That is, use proper mnemonic branch instruction names, rather than referencing SREG bits.
• If my arithmetic was correct and your branch tests were fixed, your rate would be off by a factor of two.  To fix this problem, you could replace one of the more problematic tests (testing for carry clear after cpi r17, 128) with cpi r17, 0 followed by a breq, and change the prescale factor to 256 instead of 1024, which gives 256/16M · 256 · 256 seconds, or about 1.05 seconds.
• Use named constants for register names instead of 0x04, 0x05, 0x25, and 0x26.
• Instead of your lengthy toggle sequence use EOR to toggle the value.  That is, replace
    cpi r16, 0b00000000     ; Check if r16 is set to LED OFF
    brbs 1, switchon        ; If it is, change it to ON
    ldi r16, 0b00000000     ; Otherwise, change it to OFF
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock
switchon:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock

with
    eor   r18, r16          ; Toggle LED bit
    out   PORTB, r18        ; Set the LED to the new state
    rjmp  loop              ; Go run the clock

where r16 and r18 are initialized as follows in setup:
    ldi r16, 0b00100000     ; bit mask for LED pin
    mov r18, r16


text:
Printing decimal numbers
I made simple sketch that generates three random numbers and then calculates the average of these three random numbers.
It divides the total by 3 and then displays that average number with serial.println.
Sometimes the generated average number can be decimal (for example 261,333333 or 124,33333).
Interestingly, the serial print doesn't print in decimal format 124,33333
it prints just integer 124.
How do I print the value in decimal?

Please show your code. Without that we can't help you.

Please edit your question, and post your code. How have you declared your variables, as ints or floats?

In languages such as C or C++ there is a distinction between integer types and floating-point types. You see, computers work using bits. A bit is either 0 or 1. A bit obviously lack in both range and precision, so we combine multiple bits in order to improve.
Integral Types
A byte is a group of 8 bits. In C, the type used is either
uint8_t x; // Values from 0 to 255.
int8_t  x; // Values from -128 to 127
char    x; // Values from the ASCII character set (still -128 to 127)

On Ardiuno Uno, an int is a group of 16 bits:
uint16_t c; // Values from 0 to 2^16-1 = 65535, synonym: unsigned int (Arduino)
int16_t  c; // Values from -32768 to 32767,     synonym: int (Arduino)

A long is a group of 32 bits:
uint32_t v; // Values from 0 to 2^32-1 = 4,294,967,295 = 4 GiB (unsigned long)
int32_t  v; // Values from -2,147,483,648 to 2,147,483,647 (long)

There is also usually support for 64-bit numbers, but we try not to use them in Arduino code. The reason is that most Arduino MCUs use 8-bit registers, so 64-bit operations such as "add", "sub", etc. would be very slow.
Note: Different architectures use different numbers of bits for these types. In order to be compatible with other architectures, use int32_t etc. to be sure.
Literals and Casts
Oftentimes, the compiler can not see what type a literal value is supposed to be. In C, the compiler picks a default which is usually larger than you would like. For this reason, it is useful to know how to specify a literal exactly with the type:
 ((uint8_t)200)   // Casting 200 to an unsigned 8-bit integer
 ((char)65)       // Making the ASCII letter 'A'
 ((int32_t)42)    // Force 32 as a signed 32-bit integer (long)
 42L              // The 'L' suffix does the same as above

Division and Remainder
A common cause of problems when programming in C is the division operator /. If the operands are both integer types, the result will also be an integer. So 1/3 is in fact 0. You can get the remainder of the division using the modulus operation %. For instance:
void show_division(int n, int d)
{
    Serial.print("The division: ");
    Serial.print(n);
    Serial.print(" / ");
    Serial.print(d);
    Serial.print(" equals ");
    Serial.print(n / d);
    Serial.print(" with a remainder ");
    Serial.println(n % d);
}

Floating-point Types
All of the above types are integrals, so they do not support any fractional value. Therefore C defines two different floating-point types: float and double. The former is a 32-bit value and the latter is a 64-bit value. The way it works is that the bits are split in 3:

A single bit is used for the sign.
A certain number of bits represent the fractional part, the mantissa.
The rest of the bits are used for the exponent.

As an example, the 32-bit float value representation for 1.25 is
seeeeeee_emmmmmmm_mmmmmmmm_mmmmmmmm = s * 2^(e-127) * (1.m...)_2
00111111_10100000_00000000_00000000 = (+1) * 2^(127-127) * (1.0100)_2
// Note: Binary 1.01 equals 1.25 in decimal

For performance, use the f suffix
Although 64-bit doubles are very accurate, the resulting code will run much slower. I, therefore, recommend using 32-bit floats instead. It is useful to know that you can tack on an f after the floating-point literal:
(a + b + c) / 3.0f; // Make sure to divide using 32-bit operations.

If a, b and c above are integer types, the additions will also be integer additions. When the compiler sees an int divided by a float, it will convert the int to a float, and then perform a float division. This is slow, but certainly faster than a double division.
The compiler is smart, but it doesn't hurt to help it. There is only a very small precision loss in converting this to a float multiplication:
(a + b + c) * (1.0f / 3.0f);

The compiler will pre-calculate (1.0f / 3.0f), so you get a much faster floating-point multiplication (in addition to the int to float cast).
Note: Arduino Uno defaults all floating point literals to 32-bit, and double is the same as float. Therefore, the f suffix is strictly not needed. It is still good practice to add these for compatibility with other architectures.

Your answer would be correct on many CPU architectures. However, the question is tagged “arduino-uno”, which implies an AVR architecture, and there are three specific details in your answer which are incorrect in this specific architecture: 1) chars are signed. 2) ints are 16 bits, not 32. 3) doubles are 32 bits, just like floats. Then, obviously, the f suffix has no effect at all. Could you please fix your answer?

Thanks, I will. Note though, that I do mention that in the int section.

In the C family of languages, if you divide an integer by another
integer, the compiler interprets the division operator (/) as an
integer division, i.e. you get the integer part of the quotient. Thus,
(first_int + second_int + third_int) / 3

is an integer.
If either operand is a floating point number, then the other one is
implicitly converted to floating point, and you get a floating point
division. Thus
(first_int + second_int + third_int) / 3.0

is a floating point number, and the result you expect.

shouldn't one of your variables in the second code line be a float? All ints divided will still be an int

3.0, as any constant having a decimal point, is a floating point number. As opposed to 3, which is an int.


text:
Arduino capacitive touch sensor help
So I have been messing around with the Arduino Capsense library with the immensely helpful guide; http://www.instructables.com/id/How-To-Use-Touch-Sensors-With-Arduino/  (many thanks to DangerousTim!)   using the code provided, i managed to get a relay to operate with a sensor.  It worked great and I was able to adjust the distance and sensitivity.  But when i tried adding another sensor and relay, it stopped working.  I've been trying to isolate the problem for a while now and have gotten nowhere.  I'm hoping someone can help me, here's the original code for the single sensor and relay;
#include <CapacitiveSensor.h>
#include <CapacitiveSensor.h> //change '42' to any desired pin...

long time = 0;
int state = HIGH;
boolean yes;
boolean previous = false;
int debounce = 200;
CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
// To add more sensors...
//CapacitiveSensor   cs_4_6 = CapacitiveSensor(4,6);        // 10M resistor       between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
//CapacitiveSensor   cs_4_8 = CapacitiveSensor(4,8);        // 10M resistor  between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil

void setup()
{
    cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
    pinMode(13, OUTPUT);
}

void loop()
{
    long total1 =  cs_4_2.capacitiveSensor(30);

    if (total1 > 60){yes = true;}
    else {yes = false;}

    // to toggle the state of state
    if(yes == true && previous  == false && millis() - time>debounce){
        if(state == LOW){
            state = HIGH; }
        else state = LOW;
        time = millis();
    }

    digitalWrite(13, state);
    previous = yes;
    delay(10);
}

and here's the code for the two sensors and relays
#include <CapacitiveSensor.h>

int led = 13;
int led2 = 12;
long time = 0;
int state = HIGH;
long time2 = 0;
int state2 = HIGH;
boolean yes;
boolean previous = false;
boolean yes2;
boolean previous2 = false;
int debounce = 200;

CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);        // 10M resistor  between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

void setup()
{
    cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
    cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);  //Calibrate the sensor...
    pinMode(led, OUTPUT);
    pinMode(led2, OUTPUT);
}

void loop()
{
    int total1 =  cs_4_2.capacitiveSensor(30);
    Serial.println(total1);
    int total2 =  cs_5_7.capacitiveSensor(30);

    if (total1 > 60){yes = true;}
    else {yes = false;}
    if (total2 > 60){yes2 = true;}
    else {yes2 = false;}

    // to toggle the state of state
    if(yes == true && previous  == false && millis() - time>debounce){
        if(state == LOW){
            state = HIGH;
        }
        else
            state = LOW;
        time = millis();
    }

    if(yes2 == true && previous2  == false && millis() - time2>debounce){
        if(state2 == LOW){
            state2 = HIGH;
        }
        else
            state2 = LOW;
        time2 = millis();
    }

    digitalWrite(led, state);
    previous = yes;
    digitalWrite(led2, state2);
    previous2 = yes2;
    delay(10);
}

Maybe you wired sensor cs_5_7 to pins 5 and 7, as it's name misleadingly suggests...

I think you are making a mistake initializing cs_5_7.
CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

You are using same pin 4 for both Capacitive sensors. Try using different pins. I am quite sure that, this would help.

The library documentation says it's OK to share the send pin among several sensors.


text:
Arduino Hardware serial library with rts/cts flow control support
Does there exist (any user developed etc.) version of the Hardware UART serial library that has support for RTS/CTS based flow control?
More interested in the Tx side (Arduino sends data, while the peripheral can back-pressure). The library should enable the Arduino to stop transmitting within 1 character of seeing a 'not ready' indication from the peripheral.
Thank you.

This library may help for the AVR-based Arduinos: https://github.com/i-am-bigmike/HardwareSerial_flow_control

I am not aware of any such library. You could try to implement one
yourself, and maybe share it with the community. :-)
If you take this route, you will have to copy the file
HardwareSerial.cpp from the Arduino core, make your
changes there, and have your version replace the one from the core. Here
are some ideas that may help to get you started:

Wire the 'ready' signal from the device to an interrupt-capable pin of
the Arduino.
Inside the interrupt handler:

when 'ready' is deasserted, disable the UDRE interrupt by issuing
cbi(*_ucsrb, UDRIE0)
when ready is asserted, enable it again, but only if the output
buffer is not empty:
if (_tx_buffer_head != _tx_buffer_tail) sbi(*_ucsrb, UDRIE0);

Patch HardwareSerial::write() to enable the interrupt only if
'ready' is asserted.
Note that the UDRE IRQ can be explicitly called
by HardwareSerial::flush()
and by HardwareSerial::write() if interrupts are globally
disabled. You will have to condition this on the 'ready' signal.
Note also that HardwareSerial::write() can write directly to the
UART if the buffer is empty. This also has to be
conditioned on the 'ready' signal.

I believe that CTS would be fairly easy to implement:
void loop() {
  uint8_t clear_to_send = digitalRead(CTS);
  volatile char data;
  if (clear_to_send) {
    Serial.write(data);
  }
}

I'm not sure about RTS.

This wont work to stop the transmission within a one (or even a few) characters, because although you stopped the Serial.write, there may already be data in the serial buffer (default 64bytes I think in Arduino lib) that could continue to go out (and potentially lost).
Anyways, I shifted to Teensy, which has hardware based RTS/CTS flow control, so it is capable of stopping as soon as (i believe 1 character) CTS is deasserted

Hardware USART is better for sure. Though, you could flush the buffer Serial.flush() after every write and    store the last sent byte to be sent later.

I'd be surprised if there is no Arduino implementation. Usually, the (hardware) send buffer on an UNO is, I believe, 1 byte. The Arduino serial wrapper has it's own software buffer implemented. You could change it there. But you may have to retrigger the sending manually (since I think they use the "tx complete interrupt" to wait for the next possible send, which won't happen if you stop the sending)

I have I discovered that RTS/CTS may be implemented in genuine Arduinos, but is not supported by Arduinos that use the CH340 USB to serial chip. I found this when my JAVA program could talk with a genuine Uno ok, but didn't send any data to several Arduino compatibles that use the CH340 chip (but did receive from them). I had RTS/CTS set on the JAVA program. When I changed it to FLOWCONTROL_NONE it started working just fine.

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


text:
Arduino and 2 Adafruit Fingerprint modules working together
I want to do a project with fingerprint access control. But my client wants one on both sides of the door (inside and outside). Now I am using this product Adafruit Fingerprint module but I don't want to enroll each person on each fingerprint module. I want to look at enrolling each employee on 1 of these modules and then via arduino "SYNC" the fingerprint models between each other. Is this possible? Can someone maybe point me in the right direction or am I just insane HAHAHA. Look I can do the route of programming/enrolling each person on each module. But we life in a real world and at some point the fingerprint model/id's are not going to match up. And then there is going to come a problem with my online software. As well sorry for my bad lanuage  :)

How many Arduinos are you using? Describe your current setup. How are the Arduino(s) achieving internet connectivity? What is the nature of your web server?

Current setup is each fingerprint module has its own arduino uno. But ideal I just want to use 1 arduino and have both connected. I am using a ESP8266 loaded with the arduino IDE which connects to my Linux Server/Website

TisteAndii Is that using an adafruit fingerprint library, another one or are those direct commands that can be sent over serial to the fingerprint module?

You should get an Arduino Mega, if you arent using one already. You'll need the SRAM and Serial ports.
When I used this module, I didnt have enough time to experiment with it but here goes:
The enroll command for the FPM10 sensor takes an image of a fingerprint, processes it and finally creates a 512-byte model/template that is stored in flash memory with a unique ID (PageID) and used for future comparisons. However, it is also possible to read those templates from the flash memory with a few commands.
You have not said much about the role your web server plays here, so I'll assume its possible for you to store data easily and that its responsible for authorizing fingerprint enrollment and deletion. Since you have more than one sensor, a general solution to your problem would be:

The server must keep a record of available fingerprint IDs
When instructing the Arduino to begin enrollment, the server must also send along a fingerprint ID, based on its records of what ID is free. IDs may be assigned sequentially at first but templates may be deleted, leaving holes, hence the need for the server.
The Arduino begin()s the current sensor where the user is located and performs the normal enrollment. As soon as enrollment is done, the template that was just stored, should be loaded by the Arduino from the module's flash library and into one of its character file buffers using the LoadChar command. The only parameters for this command are the BufferID and the PageID.
Then the Arduino should download the template from the character file buffer into a 512-byte buffer that you will create in the Arduino SRAM. The command needed here is the UpChar command and its sole argument is the BufferID of the buffer to be read from. As soon as confirmation is received from the module, the sensor begins sending the 512-byte template in packets of 32 bytes (by default), each with a packet identifier of 0x02 until the last packet which has a package identifier of 0x08.
Then the Arduino begin()s the other sensor and sends the DownChar command to the module, which tells the sensor to expect a template to be stored in one of its character buffers (must be specified in the command). Once the Arduino receives confirmation, it should start sending the template to this sensor, using the same packet size and format that has been set for that sensor 9or the default I mentioned before if it hasnt been changed).
Finally, the Arduino sends the Store command to the sensor, to store the template in the buffer you just wrote to, into its flash library using the same fingerprint ID it was stored with in the first sensor.
The Arduino may then send confirmation to the Linux server, which then adds the fingerprint ID to the list of used IDs.

Now both sensors have identical fingerprint libraries and may be used to match fingerprints and get the same results. Deletion of fingerprints may also follow the same process: the server commands the Arduino to delete a print with a given ID and the Arduino sends the DeleteChar command to both sensors. All the commands I mentioned here are in the sensor's datasheet, which you must have downloaded along with the Adafruit library.
Use 57600 baud to communicate with the sensors, for reliable results. This is my fork of the Adafruit library with more functions available and without the buffer overflow issues. It should make the interfacing tasks a lot easier.

This is excellent. Thank you so much! I now have a clear line to work with!

Yes, you can easily do that. This finger Print sensor works over Serial communication.
You can have multiple Serial devices connected to your Arduino UNO using SoftwareSerial library.
All you have to do is to create multiple instances of Adafruit_Fingerprint initialized with different SoftwareSerial objects. i.e.
// pin #2 is IN from sensor1 (GREEN wire)
// pin #3 is OUT from arduino to sensor1  (WHITE wire)
// pin #8 is IN from sensor2 (GREEN wire)
// pin #9 is OUT from arduino to sensor2  (WHITE wire)
SoftwareSerial mySerial1(2, 3);
Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&mySerial1);
SoftwareSerial mySerial2(8, 9);
Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&mySerial2);

Now, you can use finger1 and finger2 for your finger print operations. (previously referenced as only finger)
In order to understand Serial Communication with multiple serial devices, have a look at this Arduino.cc Offical tutorial.
Hope it helps.


text:
Arduino Yun Python ImportError: No Module named mime.multipart
So, I have an Arduino Yun, and I'm trying to send an email with python. I have this code that I got from https://github.com/amicojeko/YouCantTouchThis

But when I try to call the file with $python sendemail.py test.png, it returns me an error:

ImportError: No module named mime.multipart

I already tried to change to lowercase the imports, but it keeps showing the same error. The python version in the Arduino is 2.7. I've read something about module reorganization but even with the changes the error keep showing. Here is the code:

# coding=utf-8
# Copyright (C) 2014  Stefano Guglielmetti

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import smtplib, os, sys
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

#From address, to address, subject and message body
from_address    = 'FROM_ADDRESS@EMAIL.COM'
to_address      = ['YOUR_ADDRESS@EMAIL.COM']
email_subject   = 'Alert!!! Zombies!!! Ahead!!!'
email_body      = 'A non dead intruder has been detected and needs to be eliminated!'

# Credentials (if needed)
username = 'EMAIL_LOGIN'
password = 'EMAIL_PASSWORD'

# The actual mail send
server = 'smtp.gmail.com:587'

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
    assert type(send_to)==list
    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(f,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)

    smtp = smtplib.SMTP(server)
    smtp.starttls()
    smtp.login(username,password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

send_mail(from_address, to_address, email_subject, email_body, [sys.argv[1]], server) #the first command line argument will be used as the image file name

post the complete traceback i.e. the error.

mime.multipart isnt used in your code at all so you shouldn't be getting that error. The correct import statements for Python 2.7 are:
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email.encoders import Encoders

Study these examples in the Python 2.7 documentation.

Ok, I've done this and it worked perfectly. I had a little trouble with the Gmail server after on but it was a simple trick.


text:
Arduino: pins still active after entering sleep mode
I'm writing an Arduino sketch to control a display with my Arduino Nano. I have wired it up as explained here, but used pin 3-7 instead of pin 2-6 listed in the example. The reason I did so is that I also added a push-button on interrupt 0 (= digital pin 2). I'm calling the sleep mode with a method, as explained in the section "Example" here. The Arduino seems to sleep, turning off all LEDs but the on/off one. The problem I have now is that the LCD display is sometimes still enabled (but only sometimes, not always). Why is it behaving like this? And how can I switch off everything possible to save as much energy as possible?
Here is my code piece:
int buttonPin = 2;

void setup()
{
  pinMode(buttonPin , INPUT);
  digitalWrite(buttonPin , HIGH);
  ...
}

void loop() {
  ...
  if(counter == 100) {
    enterSleep();            // Enter sleep method!
  }
  delay(1000);
}

void enterSleep()
{
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  attachInterrupt(digitalPinToInterrupt(2), wakeUpNow, LOW);
  sleep_mode();

  /* The program will continue from here. */
  /* First thing to do is disable sleep. */
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(2));
}

void wakeUpNow() {
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

I see nothing related to an LCD there at all. Maybe you forgot that bit?

The LCD is the main part of my question. I need to know why it won't be switched off when arduino is going to sleep

The LCD might be in your question, but it's not in the code. Are we supposed to just guess what you're doing with it?  http://snippets-r-us.com/

Simply put: how are you turning off the LCD?

I don't do anything special to turn the LCD off. After making some lcd.setCursor(x, y) and lcd.write("message") I'm calling the enterSleep method. I thought that the commands inside this method switch off all output to the pins.

Nope. It stops the CPU, nothing more. It is up to you to place pins into states that you want them to be in.  If you are using PWM to set the back light brightness then it'll be random as to whether the pin is HIGH or LOW at the moment you sleep.

Ah yes, thank you, then this is the solution for me! I thought that all outputs are also "cancelled" if the sleep mode is entered! So I can easily set all pins to LOW in the enterSleep method before calling sleep mode command?

Nope. CPU core is stalled, and most peripherals are also disabled - mainly because the clock ceases to tick.  Nothing is actively changed in the configuration of anything.

Is the button bouncing? Would explain the 'sometimeness`.

The problem is that you are not specifically doing anything to "turn off" the LCD (that is, switch off the back light - note that the LCD module will still be consuming power while you sleep).
When you sleep the MCU it does just that - it goes to sleep. Its clock stops ticking. Not a lot more than that really.  So if you are using PWM to control the backlight of the LCD, when the clock stops ticking the PWM will stop happening, and the I/O pin will remain stuck in whatever state it happened to be in at that moment - leaving you with random on or off at sleep time.
The solution? Manually turn off the backlight just before you sleep.
digitalWrite(9, LOW);

To save more power you might want to consider adding a high-side switch to the power of the LCD module. With that you can physically disconnect the power to the LCD to stop it consuming any power at all during sleep mode. Of course, after re-enabling it you will need to fully reinitialize the module.
The same goes for any other external hardware that takes a power supply.
A high side switch can be built from a P-channel MOSFET being controlled by an N-channel MOSFET. There's plenty of examples on the web.


text:
How to use voltage divider between ESP8266 (3.3v) and IR proximity sensor (5V)?
I am a software developer and I don't know much about circuits so I need help.
I have an ESP8266 (esp-12) 3.3V and I'm planning to use it with an IR proximity sensor (runs between 4.5-5V). I have 2 AA batteries (3V total) and 4 AA (6V total) power supplies. Also, I have a bunch of 10K Ohm and 330 Ohm resistors.
How can I use a voltage divider to supply sufficient voltage to these components, based on what I have? If it would help, I have a 100uF capacitor and I use a CP2102 to TTL Serial Converter to program. Any help will be appreciated. Thank you in advance.

You want to use a voltage divider to POWER your boards?!?!?!

Yes, i already use esp8266 with 3v (AA batteries ) but now i want to connect it to the sensor which is 5v.

My experience with esp8266 tells me that if you power esp8266 with a 3.3V supply and you provide 5V/0V signal to its pins (either Tx/Rx or pin0,1) nothing's gonna happen. It will work fine.
Based on this experience, i would like to suggest you to

power your esp8266 with 3.3V pin of your TTL converter
power your IR sensor using 5V output pin of your TTL converter
connect signal pin of IR sensor to your esp8266 digital pin. (just
in case esp8266 heats up, disconnect circuit and try using voltage
divided only for this particular connection.

If using those external power supplies don't forget to common GND (or -ive terminal) of those power supplies.

Thank you for the advice. I was thinking of powering the Esp8266 with 3.3V batteries and the sensor with 4 AA batteries 6V(keep in mind this takes up to 5V so i wonder if that would be ok?).And signal wire of the sensor to GPIO12 OR 14 (I am using ESP-12)

you can check that in datasheet of your IR sensor. i.e. What is the maximum voltage you can apply.
you can also connect signal wire to esp8266 GPIO12/14 using voltage divider. that would also be perfectly ok.

Data sheet says maximum absolute rating supply voltage is -0.3 to 7. Recommended Operating supply voltage is 4.5 to 5.5v, so i am not sure if that is ok. If i do voltage divider how many/which resistors should i use , i have 10k and 330 ohm?. Thank you again.

No, you don't need voltage divider now. its perfectly ok. Go ahead and be careful, for things like never fail to surprise you.


text:
Library LiquidCrystal_I2C don't work in other class (Composition)
Good afternoon, I'm trying to use a class to streamline the writing on the LCD. In this class I have an private attribute (it's a pointer, do not know how I call him) called  LiquidCrystal_I2C* _lcd, I instantiate it in the constructor, so far so good, but when I call the _lcd-> begin (20, 4) the code below is not executed, but no error is displayed.
Display.h:
class Display{
    public:
        Display();
        ...
    private:
        LiquidCrystal_I2C* _lcd;
        ...
}

Display.cpp:
...
Display::Display() {
    _lcd = new LiquidCrystal_I2C(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
    _lcd->begin (20, 4);
}
...

Program.ino
#include "Display.h"

Display lcd;

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

void loop() {
    Serial.println("test");
    delay(3000);
}

Just I noticed the error when I saw that Serial.println ("test"); was not running. If I comment the _lcd->begin (20, 4); everything works.
I tested writing everything in Program.ino and worked, has nothing to do with connections or something, just do not apply the concept of composition with this class.
Can someone help me? And sorry for the English, i'm from Brazil. Thanks.

Do you understand the concept of static access in classes?

If it is as Java, I understand

It is pretty much the same, yes.  Accessing member variables with Display:: in front of them accesses the static class members, not the object local members. I am quite surprised it compiled actually like that.

I removed the Display::, but still does not work.

Is it now: _lcd = new LiquidCrystal_I2C(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
_lcd->begin(20, 4);

@Majenko static variables in C++ have to be declared static. Just putting Display:: in front of them would not turn them from instance variables to class variables.

@JayEye That's why I was questioning if it really compiled.

Got it. Sorry.  // more characters so I can post a comment :)

Most likely cause
You are hitting an insidious problem that even experienced C++ programmers frequently miss: order of initialization of global variables. In your case, Display lcd is initialized (i.e., its constructor is called) before main() and subsequently setup() are executed. However, you almost certainly are #includeing whatever library is declaring the LiquidCrystal_I2C class, probably Wire.h, and so on. In many of these classes, a global variable of that type is also defined to make it easier to access stuff. For example, Serial (as in Serial.println("foo")) is really a global variable of the appropriate type of whatever serial implementation your particular core is using.
The problem you are hitting is that the C++ standard does not guarantee the execution order of the constructors of global variables. The order is an artifact of the compiler, the order in which object files were linked, and probably the phase of the moon :)
What is (almost certainly) happening is that the constructor for your class Display is being called, which initializes the LCD and the i2c bus, and then something else calls either the LCD constructor or the i2c constructor and messes things up.
OK, "how do I fix this?" I hear you ask. Simple: make the global lcd variable a pointer, and allocate the instance in begin(), like so:
#include "Display.h"

Display *lcd;

void setup() {
  Serial.begin(9600);
  lcd = new Display();
  // stuff
}

void loop() {
  // more stuff
  lcd->some_method(some_argument);
  // even more stuff
}

Now you are guaranteed that your code will be the last to touch any initialization code that might affect the display or the bus. Just keep accessing the class Display methods through the pointer.
A less likely cause
It is still possible that your constructors are getting executed in the right order, but your hardware does not like being initialized twice (but test that anyway!), so you may have to figure out how to reset the hardware so you can initialize it again. If I understand your posting correctly, the loop never runs, which means that a second initialization probably either causes a exception (which you would not see unless you had some kind of additional debugging channel; in the case of the ESP8266, for example, that would be the output-only Serial1 port, and even then, you'd have to explicitly turn on debugging. Each core has its own debugging stuff, I forget what the real Arduino does.)
Hope this helps.
/ji

It working! Thank You =D And sorry for the delay, I was without Internet...

Another satisfied customer :)


text:
Arduino IDE installation Problems
When installing the IDE there are many "Unable to open *.DLL", errors. I check "ignore errors" and the IDE installed. Now when selecting the correct port and  board the blink sketch is uploaded and several ATK 500 errors result. I have uninstalled and reinstalled the IDE several time, with repeated results.

You should check to make sure that your Java installation is up to date. It would also be best to make sure that you're bit types between the Java environment and the Arduino IDE are the same(32bit with 32bit, 64bit with 64bit). If this does not work, you should post your actual errors so we can help more :)

I updated my Java and that solved the problem. I appreciate your help Brad.


text:
Having 3 buttons with only 2 input pins
for the purpose of learning, I'm trying to have a kind of digital/binary input where I'm using 3 buttons but only 2 input pins.
I thought of
01 = Button 1
10 = Button 2
11 = Button 3

My first attempt was like this:

I left the resistors out right now. The problem here is of course, that it doesn't matter what button I press, both LEDs are lighting up.
I used 2 Diodes in my second attempt:

This time, S1 and S2 work as expected, but S3 brings only one LED up.
Now I was wondering how I can wire things up correctly, using as little components as possible and having in mind, that I'm going to use an Arduino instead of the LEDs.
Thank you for any help!

The logic of your second attempt is perfectly correct.
If you put resistors in series with the LEDs you may get more joy out of it. Having two LEDs in parallel without resistors often results in one LED lighting and the other not.

Thank you for the hint with the resistence. Had some 75 ohms laying around and now it's working!


text:
How to get neopixel to fade colorwipe?
I'm trying to get a fade to happen when an LED turns on/off during the color wipe rather than just abruptly turning on/off. I'm not quite sure how to do this though.
#include <Adafruit_NeoPixel.h>

Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, 3, NEO_RGBW + NEO_KHZ800);
void setup() {
  strip.begin();
}

void loop() {
  colorWipe(strip.Color(255, 255, 255), 150); // Red
 colorWipe(strip.Color(0, 0, 0), 150); // Red
 delay(5000);
}

void colorWipe(uint32_t color, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, color);
      strip.show();
      delay(1000);
  }
}

This works! Just had to uncomment the delay within the while

You could change the intensity of each colour in steps till you get to your target colour.
void colorFade(uint8_t r, uint8_t g, uint8_t b, uint8_t wait) {
  for(uint16_t i = 0; i < strip.numPixels(); i++) {
      uint8_t curr_r, curr_g, curr_b;
      uint32_t curr_col = strip.getPixelColor(i); // get the current colour
      curr_b = curr_col & 0xFF; curr_g = (curr_col >> 8) & 0xFF; curr_r = (curr_col >> 16) & 0xFF;  // separate into RGB components

      while ((curr_r != r) || (curr_g != g) || (curr_b != b)){  // while the curr color is not yet the target color
        if (curr_r < r) curr_r++; else if (curr_r > r) curr_r--;  // increment or decrement the old color values
        if (curr_g < g) curr_g++; else if (curr_g > g) curr_g--;
        if (curr_b < b) curr_b++; else if (curr_b > b) curr_b--;
        strip.setPixelColor(i, curr_r, curr_g, curr_b);  // set the color
        strip.show();
        // delay(wait);  // add a delay if its too fast
      }
      delay(1000);
  }
}

To use it:
void loop() {
  colorFade(255, 0, 0, 150); // fade into red
  colorFade(255, 255, 255, 150); // and then into white
  delay(5000);
}

This is untested, so I dont know if it will be too fast or too slow. You'll have to tweak it to your needs.


text:
Dealing with TCCRx
I am totally beginner in Arduino, and i want to ask some questions :
    TCCR1B = (TCCR1B & ~(0x07<<CS10)) | (2<<CS10);

What does the previous line mean? with good explaination please .
    TCCR1A &= ~(3<<COM1A0);

for the previous line , is there difference if i wrote '1' instead of '3' ? why ?

On the first line, you clear some bits, then set some bits in the same “region” of the byte.
From inside out, get 7 (which is 3 bits of ones: 00000111), shift it upwards (the << operation) by CS10 amount (we don’t know how much, but the compiler does), complement all that (the tilde ~ character) and bitwise ‘and’ it with the value of the TCCR1A register (the & operation). Next, take a 2 (binary 00000010), shift it up by CS10 bits again (<< CS10), and bitwise ‘or’ that bit pattern with the earlier result (the | operator). Finally, assign all that to TCCR1A.
For the second line, yes, changing 3 to 1 will certainly change what happens to TCCR1A. It makes a different bit pattern, and I'm sure you can reason it out after reading the previous explanation.

Your explanation is very clear, I am surprised that I looked so much to find a site with a good explanation and I have not found!
Thank you


text:
SDS011 Dust Sensor Checksum Error
I'm working with an SDS011 particular sensor through its serial interface. The spec sheet (http://inovafitness.com/upload/file/20150311/14261262164716.pdf) indicates that the second to last byte of a serial packet is a checksum equal to sum of all the data bytes.
I am using pyserial to read and interpret the serial data. Here's a snippet of the code:
import serial

def read_sensor(port):
    while True:
        header = port.read(2)
        if header == b'\xAA\xC0':
            data = port.read(6)
            checksum = port.read()
            tail = port.read()
            if tail == b'\xAB':
                return header + data + checksum + tail

port = serial.Serial(port=MY_PORT)
packet = read_sensor(port)
data_sum = sum(packet[2:8])
checksum = packet[8]

if data_sum == checksum:
  print('Ok')
else:
   print('Error')

However, I haven't got a single packet whose checksum hasn't been an error. Is there anything I could be potentially doing wrong?

Generally, a checksum byte is computed using 8-bit arithmetic, with overflow ignored.
The Python sum function uses arithmetic of indefinite precision (eg, 32- or 64-bit words for small values, with additional words for larger numbers).
Try comparing checksum to data_sum % 256.  If that doesn't fix the problem, print out some of the data packets and checksum values so that you can use a calculator to test different combinations.

data_sum % 256 fixed it. I thought it was strange that data_sum values were greater than a byte. Should've just checked the first byte!

I assume MY_PORT stands for COMxx. Since you set no timeout, it means port.read() will block till it gets the number of bytes requested. I suggest you add a print() to display the bytes returned, if any.
To get the sum, use data_sum = sum(packet[2:8]) & 0xff to ensure you only get a byte. Also add port.reset_input_buffer() right before you call read_sensor(), to flush the input buffer.
It would also be a good idea to take at least 3 consecutive readings from the sensor in case of any errors in the first reading right after opening the port. Dont forget to add a port.close() at the end of your code.


text:
FlySky TH9X with Arduino: cant get pulseIn() function to return sensible values for any channel
So I've got a FlySky TH9X and I'm trying to read some pulses using an Arduino Uno.
I'm just starting out so I want to get the hang of using the pulseIn function before moving onto interrupts. My problem is that, when I wire everything up, I don't get sensible values. Furthermore, they don't change even though I move around the sticks on the actual remote.
I tried to start off simple by wiring just the channel 1 of the receiver to pin 3 of the Uno. Then I used this code:
int ch1;

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

void loop() {
  ch1 = pulseIn(3, HIGH, 25000);
  Serial.print("Channel 1: ");
  Serial.println(ch1);
  delay(100);
}

The serial monitor then spits out numbers ranging from 0 up to 10000+ in a very erratic and apparently not periodic nature. I'll copy a few lines here:
Channel 1: 9989
Channel 1: 10063
Channel 1: 10068
Channel 1: 274
Channel 1: 0
Channel 1: 10085
Channel 1: 10039
Channel 1: 10336
Channel 1: 9629
Channel 1: 9959
Channel 1: 10064
Channel 1: 10088
Channel 1: 378
Channel 1: 0
Channel 1: 10044
Channel 1: 10059
Channel 1: 10424
Channel 1: 9632
Channel 1: 9867
Channel 1: 10069
Channel 1: 10067
Channel 1: 10473
Channel 1: 10037
Channel 1: 10063
Channel 1: 10063
Channel 1: 10253
Channel 1: 9677
Channel 1: 10013
Channel 1: 10064
Channel 1: 10062
Channel 1: 13

As you can see: not only are the higher-end values a whole order of magnitude too big (i thought pulses are normally between 1000 - 2000us?), but the actual range that these numbers span is far, far too wide for me to do anything with. Also, the sticks on my remote seem to have no influence on the numbers.
Can someone please help me? thank you :)
Hassan

The code looks good - at least it looks just like the code given in the docs for PulseIn().  What numbers do you get if you disconnect the receiver and tie the pin to ground or VCC?  What happens if you increase the delay from 100ms up to something like 5000 (5 seconds)?

Have you checked the RX is paired to the TX, and the correct mode is selected? Might be worth using it in an RC model to check it works as expected.  The other thing to try is to see if you can get a sensible/expected reading on an oscilloscope from that channel?

What are the shape of the pulses? Your displays themselves at 9600 baud are likely to take around 21 ms, which could be throwing out your interpretation of the data.

I'm voting to close this question because it has been abandoned for months with none of the requested detail to make it answerable ever being provided and the poster has not even returned to this site since the day the question was asked.

I would not recommend using pulseIn for reading values from the receiver.  pulseIn blocks the program until a signal is received, which is almost always undesirable.
An alternative approach would be to use CHANGE interrupts.  You get an interrupt when the signal goes high and low.  You take note of the time that each change occurs with millis and compare the times to get the duration of the signal.
Here's an example - you can add more channels if you'd like.  Note, this is using the EnableInterrupt library.
#include <EnableInterrupt.h>

#define SERIAL_PORT_SPEED 57600
#define RC_NUM_CHANNELS  2

#define RC_CH1  0
#define RC_CH2  1
#define RC_CH1_INPUT  A0
#define RC_CH2_INPUT  A1

uint32_t last_update_time = 0;
uint16_t rc_values[RC_NUM_CHANNELS];
uint32_t rc_start[RC_NUM_CHANNELS];
volatile uint16_t rc_shared[RC_NUM_CHANNELS];

void rc_read_values() {
  // read the values out of the shared, volatile array (which can change at any time)
  // and into an array that we only will only change when we call this function

  noInterrupts();
  memcpy(rc_values, (const void *)rc_shared, sizeof(rc_shared));
  interrupts();
}

void calc_input(uint8_t channel, uint8_t input_pin) {
  // This is the interrupt.  If the pin is high, we record the start
  // time of the pulse.  If the pin is low, we compare the start time
  // to the current time in order to get the length of the pulse.

  if (digitalRead(input_pin) == HIGH) {
    rc_start[channel] = micros();
  } else {
    uint16_t rc_compare = (uint16_t)(micros() - rc_start[channel]);
    rc_shared[channel] = rc_compare;
  }
}

void calc_ch1() { calc_input(RC_CH1, RC_CH1_INPUT); }
void calc_ch2() { calc_input(RC_CH2, RC_CH2_INPUT); }

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

  pinMode(RC_CH1_INPUT, INPUT);
  pinMode(RC_CH2_INPUT, INPUT);

  // set up CHANGE interrupts, so that we get notified when
  // each signal goes high or low.
  enableInterrupt(RC_CH1_INPUT, calc_ch1, CHANGE);
  enableInterrupt(RC_CH2_INPUT, calc_ch2, CHANGE);
}

void loop() {
  rc_read_values();

  Serial.print("CH1:"); Serial.println(rc_values[RC_CH1]);
  Serial.print("CH2:"); Serial.println(rc_values[RC_CH2]);

  delay(200);  // just so serial log doesn't flood
}

For a more detailed explanation, take a look here:  http://rcarduino.blogspot.com/2012/01/how-to-read-rc-receiver-with.html

Hi, thank you for your answer Ryan.
However, I do still need to know what went wrong with the pulseIn function as I would like to get that working first before moving onto interrupts. Can you offer me any advice on that?
Thanks

I'd -1 this answer, but I don't have the points yet.  The questioner clearly states that they don't want to use interrupts yet, and they would like to know why the code sample outputs seemingly random numbers.

Use a bigger timeout (30000):
int rcPin1 = 3; // PWM signal arduino pin
int rcPin2 = 4; // PWM signal arduino pin
int rcPin3 = 5; // PWM signal arduino pin
int rcPin4 = 6; // PWM signal arduino pin
int rcPin5 = 7; // PWM signal arduino pin
int rcPin6 = 8; // PWM signal arduino pin
int ch1 = 0;    // Receiver channel 1 pwm value
int ch2 = 0;    // Receiver channel 1 pwm value
int ch3 = 0;    // Receiver channel 1 pwm value
int ch4 = 0;    // Receiver channel 1 pwm value
int ch5 = 0;    // Receiver channel 1 pwm value
int ch6 = 0;    // Receiver channel 1 pwm value
void setup() {
  pinMode(rcPin1, INPUT);
  pinMode(rcPin2, INPUT);
  pinMode(rcPin3, INPUT);
  pinMode(rcPin4, INPUT);
  pinMode(rcPin5, INPUT);
  pinMode(rcPin6, INPUT);
  Serial.begin(9600);
}

void loop() {
  // Read in the length of the signal in microseconds
  ch1 = pulseIn(rcPin1, HIGH, 30000);
  Serial.print("Channel #1: ");
  Serial.println(ch1);
  ch2 = pulseIn(rcPin2, HIGH, 30000);
  Serial.print("Channel #2: ");
  Serial.println(ch2);
  ch3 = pulseIn(rcPin3, HIGH, 30000);
  Serial.print("Channel #3: ");
  Serial.println(ch3);
  ch4 = pulseIn(rcPin4, HIGH, 30000);
  Serial.print("Channel #4: ");
  Serial.println(ch4);
 ch5 = pulseIn(rcPin5, HIGH, 30000);
  Serial.print("Channel #5: ");
  Serial.println(ch5);
  ch6 = pulseIn(rcPin6, HIGH, 30000);
  Serial.print("Channel #6: ");
  Serial.println(ch6);
 delay(1000);
}

Hmm, that might possibly help, but most analog RC systems repeat every 20ms, and digital systems likely faster.  It seems like with the originally 25,000 uS even if the a pulse was "just" missed another would arrive in time, but your longer allowance is probably okay, too.  If this were the solution, then changing just this one thing would presumably make a difference, and changing it back would restore the problem.


text:
Does upload using `ICSP`overwrite the bootloader?
If I compile a sketch then upload using ICSP does it overwrite the bootloader?
I am using Arduino program and Arduino Uno as ICSP.

The Arduino IDE creates an additional hex file that does also contain the bootloader. But you have to use to commandline to upload it.

Yes.
When you program using ISP you overwrite everything in the chips flash, even the bootloader.
This has some pro's and con's:

Pro: The program starts immediately, meaning it doesn't wait to check if there's any programming coming in before starting your sketch.
Con: You need to use ISP to program your Arduino again or to upload the bootloader again.

Normally there is not really any reason for not having the bootloader present but if you are programming bare Atmel chips without a serial interface this way might be preferable.

Thanks. I expected ths was the case, but I have a Nano which can't be powered/programmed by serial but works with ICSP. This seems to offer the opportunity to load a larger sketch.

Yes, it will overwrite the bootloader.
In addition to Hans Neve's list of Pros, it has the added benefit of gaining you a couple hundred bytes (0.5KB) that is otherwise used by the bootloader.


text:
Arduino Uno Multiple Modules
I have an Arduino Uno and I want to connect;

RFID Reader (RC522)
WiFi Module (ESP8266 ESP-01)
SD Card Module
RTC (Real Time Clock - DS1307)

Same time but pinouts are not enough. Is there a way to doing this with Uno or I have to buy an Arduino Mega ? I saw "Expansion Sensor Shield"s but I do not know what is the logic of using this ?
Regards

It depends. You need to provide more detail. Some of the devices use I²C which can share connections provided they have different addresses. Others use SPI which need individual select pins.

Let's see which device uses which communication protocol:

WiFi Module (ESP8266 ESP-01) uses Serial communication.
RTC (Real Time Clock - DS1307) uses I²C communication.
RFID Reader (RC522) uses SPI communication.
SD Card Module also uses SPI communication.

Now, the Arduino UNO supports One I²C, One SPI and One Serial (by default) communication port.
So, you can easily connect your Wifi and RTC modules.
Now, actual problem is: "How to access multiple SPI interfaces on Arduino" (and that is a solved problem).
Hope it helps and you don't have to buy an Arduino MEGA.