LCD display and ultrasonic sensor not functioning I am doing fish feeder project with level detection for the feeds but lcd display and ultrasonic sensor did not function.

#include <LiquidCrystal.h>
#define trigPin 12              // the trig pin to digital pin 12
#define echoPin 13              // the Echo pin to digital pin 13
#define L 8
#define M 9
#define H 10
// #define trigmotor 1 //closelid
int led = A1;           // LED indicator to digital pin A1
#include <Servo.h>
Servo MyServo;

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

const int thresholdH = 0;
const int thresholdM = 70;
const int thresholdL = 90;
// defines variables
long duration;
int distance;
float percentLV;

void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600); // Starts the serial communication
  pinMode(led,OUTPUT);
  digitalWrite(led,LOW);            //set the led off(initial condition)
  lcd.begin(16, 2);
}
void loop()
{

int degreesOfRotation = 8;
int servoPinNumber = 11;
float hoursBetweenMeals = 12;
float mealDelayTime = 0;

{
    MyServo.attach(11);
    MyServo.write(degreesOfRotation);
    mealDelayTime = hoursBetweenMeals * 1800000;
    delay(20);

    while(degreesOfRotation < 152) {
        MyServo.write(degreesOfRotation);
        delay(10);
        degreesOfRotation += 1;
    }
    while(degreesOfRotation > 8) {
        MyServo.write(degreesOfRotation);
        delay(10);
        degreesOfRotation -= 1;
    }
    delay(mealDelayTime);
}

{
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = (duration * 0.034 / 2);
  float percentLV = (40 - ( distance - 16 )) * 100 / 40;

  if (percentLV > thresholdL && percentLV < 100) {

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("PLEASE REFILL!");
    lcd.setCursor(0, 1);
    //lcd.print(distance);
    lcd.print(percentLV);
    lcd.print(" %");
    digitalWrite(H, HIGH);
    digitalWrite(M, LOW);
    digitalWrite(L, LOW);
    //digitalWrite(trigmotor, HIGH);
    //delay(3000);
    //digitalWrite(trigmotor, LOW);
    //delay(1000);
    digitalWrite (led, HIGH);      // Turn on the led indicator
    delay(20);
  } else if (percentLV <= thresholdL && percentLV > thresholdM) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("U May Refill Now");
    lcd.setCursor(0, 1);
    //lcd.print(distance);
    lcd.print(percentLV);
    lcd.print(" %");
    digitalWrite(H, LOW);
    digitalWrite(M, HIGH);
    digitalWrite(L, LOW);
    //digitalWrite(trigmotor, LOW);
    digitalWrite (led, HIGH);      // Turn on the led indicator
    delay(20);
  } else if (percentLV <= thresholdM && percentLV > thresholdH) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Take it easy");
    lcd.setCursor(0, 1);
    //lcd.print(distance);
    lcd.print(percentLV);
    lcd.print(" %");
    digitalWrite(H, LOW);
    digitalWrite(M, LOW);
    digitalWrite(L, HIGH);
    //digitalWrite(trigmotor, LOW);
    digitalWrite (led, LOW);      // Turn off the led indicator
    delay(20);

  } else {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("FULL!!");
    lcd.setCursor(0, 1);
    //lcd.print(distance);
    lcd.print(percentLV);
    lcd.print(" %");
    //digitalWrite(trigmotor, LOW);
    digitalWrite (led, LOW);      // Turn off the led indicator
    delay(20);

    Serial.print("PercentLV: ");
    Serial.print(percentLV);
    Serial.println("%");
  }
  delay(1000);

}

}

There doesn't appear to be anything wrong from a quick glance.  Have you got the right library for the LCD?

The chances are there is something wrong with your LCD.  So check your connections again.  Now create a new sketch that just prints hello world on the LCD, or better still use an example.  If that works, then the problem is an interaction between components.

So write a sketch that spins the servo back and forth while printing a message on the LCD.

Did that work, now add in the ultrasonic sensor and the code.

Now the other bits, and if that works, then you could look at what you have done differently, or just thank your lucky stars :)


How do I control the buttons on an Arduino LCD keypad shield? I have just bought a 16x2 LCD display with buttons. I can get the display to work and do various basic sketches included in the Arduino IDE. However, I cannot figure out how to control the buttons.

The buttons work using analog pin 0 and from what I was able to understand from what I have read online, it is something to do with the values you receive when the buttons are pressed. I can't seem to find out what values mine gives, I have found a sketch that is supposed to map the buttons, but I cannot get it to work, as I don't really understand what it is doing, I am very new to this.

The code I am using is as follows:

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

int lcd_key     = 0;
int adc_key_in  = 0;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

int read_LCD_buttons() {
  adc_key_in = analogRead(0);
  if (adc_key_in > 1000) return btnNONE;
  if (adc_key_in < 50)   return btnRIGHT;
  if (adc_key_in < 250)  return btnUP;
  if (adc_key_in < 450)  return btnDOWN;
  if (adc_key_in < 600)  return btnLEFT;
  if (adc_key_in < 920)  return btnSELECT;
  return btnNONE;
}

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0,0);
  lcd.print("Push the buttons");
}

void loop() {
  lcd.setCursor(9, 1);
  lcd.print(millis()/1000);
  lcd.setCursor(0, 1);
  lcd_key = read_LCD_buttons();
  switch (lcd_key) {
    case btnRIGHT: {
      lcd.print("RIGHT ");
      break;
    }
    case btnLEFT: {
      lcd.print("LEFT   ");
      break;
    }
    case btnUP: {
      lcd.print("UP    ");
      break;
    }
    case btnDOWN: {
      lcd.print("DOWN  ");
      break;
    }
    case btnSELECT: {
      lcd.print("SELECT");
      break;
    }
    case btnNONE: {
      lcd.print("NONE  ");
      break;
    }
  }
}

If anyone can give me any pointers it would be greatly appreciated.

Liam

I have found an easy way to do this, i found a tutorial on instructables that has explained in detail what to do, i then applied this to my LCD keypad shield rather than external buttons on a breadboard.

All you have to do to see what the results are for your particular buttons is to load the sketch below onto your board then open the serial mapper on the arduino ide, simply press the buttons and you should see the results.

 /*
  Debounce

  Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
  press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
  a minimum delay between toggles to debounce the circuit (i.e. to ignore
  noise).

  created 28 October 2009
  by Riaan Cornelius

  */

 // constants won't change. They're used here to
 // set pin numbers:
 const int buttonPin = 0;     // the number of the pushbutton pin
 const int ledPin =  53;      // the number of the LED pin for testing

 const int BUTTON1 = 1;
 const int BUTTON2 = 2;
 const int BUTTON3 = 3;
 const int BUTTON4 = 4;
 const int BUTTON5 = 5;

 const int BUTTON1LOW = 970;
 const int BUTTON1HIGH = 1024;
 const int BUTTON2LOW = 850;
 const int BUTTON2HIGH = 950;
 const int BUTTON3LOW = 700;
 const int BUTTON3HIGH = 800;
 const int BUTTON4LOW = 400;
 const int BUTTON4HIGH = 650;
 const int BUTTON5LOW = 250;
 const int BUTTON5HIGH = 350;

 // Variables will change:
 int ledState = HIGH;         // the current state of the output pin
 int buttonState;             // the current reading from the input pin
 int lastButtonState = LOW;   // the previous reading from the input pin

 // the following variables are long's because the time, measured in miliseconds,
 // will quickly become a bigger number than can be stored in an int.
 long lastDebounceTime = 0;  // the last time the output pin was toggled
 long debounceDelay = 50;    // the debounce time; increase if the output flickers

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

 void loop() {
   // read the state of the switch into a local variable:
   int reading = analogRead(buttonPin);
   Serial.println(reading);

   /*
   Not needed while getting the values.

   int tmpButtonState = LOW;             // the current reading from the input pin

   if(reading>BUTTON5LOW && reading<BUTTON5HIGH){
     //Read switch 5
     tmpButtonState = BUTTON5;
   }else if(reading>BUTTON4LOW && reading<BUTTON4HIGH){
     //Read switch 4
     tmpButtonState = BUTTON4;
   }else if(reading>BUTTON3LOW && reading<BUTTON3HIGH){
     //Read switch 3
     tmpButtonState = BUTTON3;
   }else if(reading>BUTTON2LOW && reading<BUTTON2HIGH){
     //Read switch 2
     tmpButtonState = BUTTON2;
   }else if(reading>BUTTON1LOW && reading<BUTTON1HIGH){
     //Read switch 1
     tmpButtonState = BUTTON1;
   }else{
     //No button is pressed;
     tmpButtonState = LOW;
   }

   // check to see if you just pressed the button
   // (i.e. the input went from LOW to a buttonState),  and you've waited
   // long enough since the last press to ignore any noise:

   // If the switch changed, due to noise or pressing:
   if (tmpButtonState != lastButtonState) {
     // reset the debouncing timer
     lastDebounceTime = millis();
   }

   if ((millis() - lastDebounceTime) > debounceDelay) {
     // whatever the reading is at, it's been there for longer
     // than the debounce delay, so take it as the actual current state:
     buttonState = tmpButtonState;
     Serial.println(buttonState);
   }

   // save the reading.  Next time through the loop,
   // it'll be the lastButtonState:
   lastButtonState = tmpButtonState;

   // set the LED using the state of the button for testing:
   switch(buttonState){
     case BUTTON1:
     digitalWrite(ledPin, buttonState>0);
     break;
     case BUTTON2:
     digitalWrite(ledPin, buttonState>0);
     break;
     case BUTTON3:
     digitalWrite(ledPin, buttonState>0);
     break;
     case BUTTON4:
     digitalWrite(ledPin, buttonState>0);
     break;
     case BUTTON5:
     digitalWrite(ledPin, buttonState>0);
     break;
   }
   */
 }

Liam


Detecting ball moving between IR pair and handling ambient light changes I plan to use the SEN-00241 IR Emitter and Detector pair to detect a ping pong ball moving fast between them.

I understand I could watch for voltage changes to detect this passing object, however how do people generally deal with ambient light changes? From my research it seems that the voltage will change with ambient light, and although I can take steps to create funnel vision between the 2 I'm sure it may still be an issue.

Would you take constant readings and find averages over 10 consecutive readings to allow for changes in ambient light and set a new baseline reading? Then if the voltage changes dramatically and only for a few reads then I know that was the ball and not to change the baseline reading.

this is the same problem that IR remote/television has; how can TV they tell if that high voltage is a direct light or a logic 1 sent by remote? Simply because remote does not send a "HIGH" signal, but a modulated one, tipically at 36KHz. This mean a logic "HIGH" is a train of "HIGH-LOW" at 36KHz (you can see it as PWM at 50%duty cicle and 36KHz frequency)

Ambient light des not have fast variation, and inside light are at 50-60Hz, so they will be "filtered" out.

So, until you see high voltage change at 36KHz, you have your beam fine, if it is not the case, then look at voltage: if fixed at normally low voltage, beam is broken; is fixed at normally high voltage then some light stronger than your emitter is "blinding" the sensor.

note that because 36KHz is a very use frequency on Remote, there a a lot of chip that will emit or read a modulated IR, but expose a normal digital input/output, but still can be done by software, expecially if hardware assistet (like PWM for output), interrupt for input


ESP8266 official library post request returns 400 Every time I try the post request I get a 400 error but the JSON and URL are identical to those that I used on an online API tester and it worked every time there. I am running this program in the official Arduino IDE and most of this code was taken from the ESP8266 official library here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h

if (http.begin(client, host)) {  // HTTP

  http.addHeader("Content-Type", "application/json");
  // Serial.print("[HTTP] GET...\n");
  // start connection and send HTTP header
  // int httpCode = http.GET();
  String request = "{ \"temperature\": 27.0, \"humidity\": 43 }";
  Serial.print("[HTTP] POST...\n");
  int httpCode = http.POST(request);

400 is a HTTP error "Bad request" sent by the HTTP server. Possible reasons for this error are malformed HTTP request line, malformed HTTP request headers, missing empty line after the last HTTP header and a request to 'secure' port without encryption.

In your case the HttpClient library constructs the HTTP request so there should be no error. Only thing you supply for the request is the URL in your case it is the variable host. As we cleared in comments, your URL started with https. The HttpClient library parsed the url, detected the https protocol and used the secure port 443. But the underlying networking Client object was not SSL so it didn't encrypt the request.


TMC26XMotorTester:44: error: 'TMC26XStepper' does not name a type I am working with a TOS-100 Stepper Driver Shield and am attempting to use the pre-written TMC26XMotorTester/Motor/Serial set of files to make it work.

I unzipped the files, copied the TMC26XStepper folder into the library directory in my Arduino folder, and restarted the Arduino IDE (as well as the Arduino and Driver Shield boards).  I also switched the DIR and STEP pins (6 and 7 swapped to match the wiring on my board).

In the TMC26XMotorTester file, I wrote

    #include <TMC26XStepper.h>

so I'm assuming (given everything I've done), that the functions should be available given this file inclusion.

However, I get the error

    TMC26XMotorTester:44: error: 'TMC26XStepper' does not name a type

along with the complete list of functions from the TMC26XStepper.h/.cpp file that were not identified.

Any thoughts?  I'm using Arduino-Uno version 1.6.9.

Arduino libraries are normally written as a C++ Class.  When you start a sketch you normally tell the compiler where to find that Class and to Instantiate that class.  If the compiler does not find the Class and you attempt to Instantiate it, the compiler will telly you it does not know what to do.  That is, it will tell you the thing you are using (TMC26XStepper) does not describe anything or is not a Type.

Study the structure of Arduino libraries to make sure what you have installed agrees with the common Arduino library.

Also, newer version of the Arduino IDE can download and unpack libraries automatically given both the IDE and the library are setup to do this.


Read Internal Registers of RS485 I am trying to interface sele EM2M, I am using Arduino Mega with RS 485 module. I want to read the internal registers I am using ModbusMaster library. The data which I want to receive is in the internal registers but I am not getting how can I read Internal registers. When I use other software to read data I am getting the out
I also wanted to know the difference between Internal Registers and Holding Registers
Another questions how are the frames formed for communication in rs485 from the above image I can understand 01 04 but from where do they get 00 1A please explain the same.

The RS485 has no internal registers, all of that is in your target unit. Hopefully the instructions for that will tell you how to do it.  Start by getting simple communications working then slowly progress from there.


wire up usb to pins rather than on board usb socket I have an uno r3 clone in an enclosure and one of these usb ports on the enclosure.

It's pretty tight in there so I was wondering if there was a way to bypass the usb port on the board and plug it in directly to the pins.

So do something like plug the usb into the outer port on the enclosure and then cut off the usb end and plug the wires directly into the board rather than using the onboard arduino usb port.

The group of 4 just above the i2c seems promising but couldn't find much on it.

Thanks for your help.

You will have to (optionally) desolder the existing USB socket and solder the wires to the pins where that socket was on the board. It connects directly to the pins of the CH340G surface mount chip (rectangular one by the USB socket) and soldering wires to those pins would be tricky.


Issues in interfacing relay with Arduino I want to control AC bulb with Arduino, 5v-relay.
My connections are

My code is

#define RELAY1  7

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

void loop()
{
  digitalWrite(RELAY1,LOW); // Turns ON Relays 1
  Serial.println("Light OFF");
  delay(15000); // Wait 5 seconds
  digitalWrite(RELAY1,HIGH); // Turns Relay Off
  Serial.println("Light ON");
  delay(20000);
}

Red LED is on according to AC bulb.
Power LED (Green colored one) is also on as I have given 5v supply from Arduino.

The issues are

Bulb is not following the delay given in the code. The output for the above code is 20sec ON - 15sec OFF -20sec ON - 15sec OFF- 20sec ON -15sec OFF -  1sec ON - 20sec ON - 15sec OFF etc. means apart from 20,15 sec duration there is a duration of 1sec is coming in between as noise. What might be the reason?
On monitor also, only first 3 actions are getting printed after that no printing is observed.

==>The relay I am using is:

what i would do is test the parts one by one.
so first look if you're signal is good by attaching a led to it.
then test you're relay with 5v.

now you should know what the problem is the arduino or the relay


What programmer do I select in Arduino IDE for the ATMEL-ICE ISP? I have been using an AVRISPmkII for many years but recently gave mine away to another hobbiest. I wnated to buy a replacement and have had to buy an ATMEL-ICE ISP as the AVRISPmkII is now unavailable.
Occasionally, I like to program the Arduino Uno from the Arduino IDE using the ISP.
However when I go to select the programmer (from the tools menu), I don't see the ATMEL-ICE in the list.
How do I get Arduino IDE to recognize the ATMEL-ICE ISP?
Note: I am using Arduino IDE v1.6.8.

As of V1.8.2, the ATMEL-ICE is now included as a programmer in the Arduino IDE.

The ATMEL-ICE was not available as a in-system programmer (ISP) in version 1.6.8 of the Arduino IDE.

On the 20th of Jan 2017, user facchinm added the ATMEL-ICE to the list of programmers in the IDE, and it was merged into the master on the 8th of Feb. It was released as a version on the 22nd of March 2017.


Making WiFi hotspot for 3G network sharing controlled by Arduino I am trying to make a WiFi internet network from 3G using Arduino as access control. I need the Arduino to act as server and control users, consumption, and connection speed. (When users connect to the WiFi, they have to enter a passcode in a webpage to use internet for a limited time,  or limited data.)

So is this possible? I still did not try anything because I can not afford to buy many objects and fail to make it work.

I am thinking of using a 3G shield and a WiFi shield, or a router connected to 3G dongle connected to an Arduino via ethernet, or a 3G shield Arduino to ethernet shield to WiFi router.

I don't know if any of these can work, so I really appreciate any guidance.

Not a chance, I am afraid (you were right not to buy things yet). Things like the 3G shield and WiFi shield don't work in the way that is needed for a WiFi hotspot like that. You're better off with a Raspberry Pi and a 3G USB dongle and run hostapd along with the other software needed for your project - things like apache, etc.

You may be able to do it with the Linux portion (OpenWRT) of an Arduino Yun with a USB 3G dongle attached, but it would be sluggish. Best to stick to something with enough processing to do what you want, which means a Raspberry Pi or similar.


On extending scrolling 8x8 bitmap to 32x32 or 32x64 (see clip) I am using an Adafruit 64x32 RGB LED panel with my Arduino Mega 2560. I tried to find/construct working examples of a 32x32 or wider scrolling text/bitmap but have failed.

The smaller version is working and is calling two functions for it to implement:

loadSprite(IMAGES2,60);
bildmittig_sprite(data,dpink,300);

IMAGES2 is of type const PROGMEM byte IMAGES2[][8] and is an array
of several 8x8 bitmaps
data is a buffer data array element,    containing the dynamic
movement of bitmaps, called in the void loop()

For the whole code here. For the video clip smaller scroller here.

For the video clip to what I would like to extend to:

   Russian Letters: http://dropbox.com/s/n2ilxqgubn83ii9/MOV_0056.mp4?dl=0
 Or Chinese Letters: http://dropbox.com/s/9rad116adc575u1/MOV_0057.mp4?dl=0

loadSprite() looks like this:

void loadSprite(const PROGMEM byte bild[][8],int anzahl) {
  for(int row=0; row < 8; row++) {
    //iterate through each row
    data[row] = 0;
    //reset the row we're working on
    for(int column=0; column < 8; column++) {
      //iterate through each column
      data[row] = data[row] + ((powers[column] & (pgm_read_byte(&(bild[index][row])) << offset)));
      //loads the current charachter offset by offset pixels
      data[row] = data[row] + (powers[column] & (pgm_read_byte(&(bild[index+1][row])) >> (8-offset)));
      //loads the next charachter offset by offset pixels
    }
  }
  offset++;
  //increment the offset by one row
  if(offset==8){offset = 0; index++; if(index==anzahl){index=0;}}
  //if offset is 8 load the next character pair for the next time through
}

The displaying function (places it i the middle of 32x32 panel) like this:

void bildmittig_sprite (byte bild[8],word cchsv, int duration) {
  for(int i = 0; i <8; i++) {
    for(int ii = 0; ii<8; ii++) {
      int bit = (bild[i] >> ii) & 1;
      if(bit == 0) {
        matrix.drawPixel(7-ii+12, 12+i, black);
      } else {
        matrix.drawPixel(7-ii+12, 12+i, cchsv);
      }
    }
  }
  delay(duration);
}

Working for 8x8 bitmaps, It eludes me how I could possible extend the coding (scrolling) for bitmaps like this:

const PROGMEM unsigned char rus5[] = {
  0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0xff, 0x03,
  0x00, 0x00, 0x78, 0x00,
  0x00, 0x00, 0x38, 0x00,
  0x00, 0x00, 0x3c, 0x00,
  0x00, 0x00, 0x1c, 0x00,
  0x00, 0x00, 0x1c, 0x00,
  0x00, 0x00, 0x1e, 0x00,
  0x00, 0xfc, 0xde, 0x0f,
  0x00, 0x8f, 0xef, 0x1f,
  0x80, 0x07, 0x3f, 0x3c,
  0xc0, 0x03, 0x0f, 0x3c,
  0xe0, 0x01, 0x0f, 0x3c,
  0xe0, 0x01, 0x07, 0x3c,
  0xf0, 0x80, 0x07, 0x3c,
  0xf0, 0x80, 0x03, 0x3c,
  0x70, 0x80, 0x03, 0x1e,
  0x78, 0xc0, 0x03, 0x1e,
  0x78, 0xc0, 0x03, 0x0f,
  0x78, 0xe0, 0x01, 0x0f,
  0x78, 0xf0, 0x81, 0x07,
  0xf0, 0xf8, 0xc3, 0x03,
  0xf0, 0xef, 0xf6, 0x01,
  0xe0, 0xf7, 0x7c, 0x00,
  0x00, 0xf0, 0x00, 0x00,
  0x00, 0x70, 0x00, 0x00,
  0x00, 0x70, 0x00, 0x00,
  0x00, 0x78, 0x00, 0x00,
  0x00, 0x78, 0x00, 0x00,
  0x00, 0x7c, 0x00, 0x00,
  0x80, 0xff, 0x03, 0x00,
  0x00, 0x00, 0x00, 0x00
};

I tried variants of concatenation, like:

4 bytes as a row, stitching together several with beforehand created
data (data1 ... data4) elements (also adjust coherence for vertical elements).
And then have them displayed at the correct place to be able to use
the existing code but so far only vertical concatenation seemed to
work briefly.

I am at the end of my wits for this project, but maybe somebody else sees a better way.

I've looked at your code briefly, long enough to get the impression that each array like rus5[] contains 32 groups of 4 bytes each, with each 4-byte group representing a row of a character.  [If not, let me know.]  Also, I read the question a time or two, but don't see specified what direction you want to scroll, and whether you will scroll a string of characters or just one character.  Anyhow, in following I suppose you want to scroll a string horizontally with characters entering at the right end of the display and scrolling off the left end.

To support horizontal scrolling, arrange your bit maps such that each group of 4 bytes represents the 32 bits of a single column of the display.  Regarding four bytes as an unsigned long, suppose the LSB (least significant bit) corresponds to the top LED in a column.  Use code like the following to set pixels, supposing cn = current column number; d = number of character columns already scrolled off, in range 0 to 31; maxCol = number of display columns; and t[] is a three-character string corresponding to three characters currently on the 64x32 display.  [That is, a right-hand part of t[0] is at the left end of display; then all of t[1] appears; then a left-hand part of t[2].]  [Generally, where this sets cc=0, you would set it to point at a current-character in a longer string, instead of at the first character in a three-character array t[]; and would advance one character each time d gets up to 32.]

cc = 0;     // index of first character to display
c = t[cc];  // first character to display
e = d;      // how far we have scrolled so far
for (cn=0; cn<maxCol; ++cn) {
  unsigned long colData = pgm_read_dword(charData[c][e]);
  for (ro=0; ro<32; ++ro) {
    matrix.drawPixel(cn, ro, (colData&1)? cchsv : black);
    colData >>= 1; // discard used-up bit
  }
  ++e;
  if (e >= 32) {  // Done with current character?
    c = t[++cc];  // Set c to next character
    e = 0;        // Start with leftmost col of character
  }
}

Edit 1: In the code above, charData[c][e] is an unsigned long int.  Its 32 bits represent column e of ascii character c, with the LSB representing the top-row pixel.  To create charData[][], write a program on your development system that reads whatever bitmaps you have now and writes out code to properly set up charData[][] in ProgMem.

Note, for initial scroll-testing, you could skip writing a development-system program to re-orient characters and instead test with character-data arrays as they are.  Characters might display sideways or upside down, but would scroll ok anyway.  Or, if bytes are not in proper Endianness to be an unsigned long, they would display in four mis-ordered slices.

Edit 2 With the following code,

void  scroller (const PROGMEM byte bildo1[][4],const PROGMEM byte bildo2[][4],int maxCol, word cchsv) {

int d = 0;
int cc = 0;
unsigned long c[32];

for(int ii=0;ii<32;ii++) {
  c[ii]=0;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][0]))<< 24;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][1]))<< 16;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][2]))<< 8;
  c[ii] += (long) pgm_read_byte(&(bildo1[ii][3]));
}
int e = d;      // how far we have scrolled so far
for (int cn=0; cn<maxCol; ++cn) {
  unsigned long colData = c[e];
  for (int ro=0; ro<32; ++ro) {
    matrix.drawPixel(cn, ro, (colData&1)? cchsv : black);
    colData >>= 1; // discard used-up bit
  }
  ++e;
  if (e >= 32) {  // Done with current character?
    for(int ii=0;ii<32;ii++) {
      c[ii]=0;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][0]))<< 24;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][1]))<< 16;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][2]))<< 8;
      c[ii] += (long) pgm_read_byte(&(bildo2[ii][3]));
    }
    e = 0;        // Start with leftmost col of character
  }
}}

chrisoutwright reports getting an image like the following [cropped from a larger dropbox.com image]:

Cutting this into 4 equal-size horizontal slices and swapping slices top to bottom, we get:

That image suggests packing the bytes in reverse order, eg via

c[ii] += (long) pgm_read_byte(&(bildo2[ii][0]));
c[ii] += (long) pgm_read_byte(&(bildo2[ii][1]))<< 8;
c[ii] += (long) pgm_read_byte(&(bildo2[ii][2]))<< 16;
c[ii] += (long) pgm_read_byte(&(bildo2[ii][3]))<< 24;

Continuing on, if we rotate the left half of the above 90° then flip the rotated image left to right we get a reasonable facsimile of the letter 春 :

The "flip left to right" amounts to reading bits out MSB first instead of LSB first.  During testing, one might do that by saying

matrix.drawPixel(cn, ro, (colData&(1<<31))? cchsv : black); colData <<= 1;

instead of

matrix.drawPixel(cn, ro, (colData&1)? cchsv : black); colData >>= 1;

but in the longer run, a development-system program should be used to re-orient characters instead of using up MCU memory space and time for bitmap organizing.

To make the characters scroll, add a parameter (eg, byte escroll) to the calling sequence.  Discard variable d if it isn't used within scroller, and instead of initializing e to d (which is always zero hence does not allow for scrolling) initialize it via

e = escroll;

In the routine that calls scroller(), say something like

byte es=0;
while (scrolling) {
  scroller(bildo1, bildo2, maxCol, cchsv, es);
  delay(msPerScrollStep);
  ++es;
  if (es >= 32) {
    es = 0;
    // do stuff here about next characters to display
  }
}

That is, call scroller() within a scroll-timing loop (or perhaps put the timing into scroller(), whichever meshes better with overall design).

Note, with the code as it stands, plus suggested changes, bildo2 will scroll in a second time1 unless a third character is supplied to scroll in.

1For example, with maxCol of 64, if es is 16, whenscroller() is called, e will go from 16 to 31 displaying the second half of bildo1, then from 0 to 31 displaying all of bildo2, then from 0 to 15 displaying the front half of bildo2.


post data from node mcu to my sql database #include <ESP8266WiFi.h>

const char* ssid = "xxxx";
const char* password = "xxxxxxxxxx";

const char* host = "192.168.43.18";
const int ldr = A0;
int val = 0;

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

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
}

void loop()
{
  val = analogRead(ldr);
  WiFiClient client;

  Serial.printf("\n[Connecting to %s ... ", host);
  if (client.connect(host, 80))
  {
    Serial.println("connected]");
    client.println("POST /past.php HTTP/1.1");
    client.println("Host: 192.168.43.10");
    client.print(val);
    Serial.println(val);
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(5000);
}

I have uploaded this code to node mcu but it get's working but the uploaded data in my database is not shown please any one help me out

My corrected code working code:

#include <ESP8266WiFi.h>

const char* ssid = "vathsal";
const char* password = "1234567890";

const char* host = "wwwkprstaffcom.000webhostapp.com";
const int ldr = A0;
int val = 0;
String data;
void setup()
{
  Serial.begin(9600);
  Serial.println();

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
}

void loop()
{
  val = analogRead(ldr);
  data = "ldr=";

  data.concat(val);
  WiFiClient client;

  Serial.printf("\n[Connecting to %s ... ", host);
  if (client.connect(host, 80))
  {
    Serial.println("connected]");
    client.println("POST /add.php HTTP/1.1");
    client.println("Host: wwwkprstaffcom.000webhostapp.com");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
    Serial.println(val);
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(5000);
}


Alternative for IRF520 mosfet in Arduino shutdown schema I’am using IRF520 mosfet according to this schema to shut down Arduino by low level on output to 10K ohms resistor

Schema of my device is

The issue is that IRF520 took too much place

Is it possible to substitute IRF520 with smaller mosfet?

Additional info:

I measured average power consumption – it’s about 22 mA on 12V = 0.264W

IRF520 is for 70W max according to datasheets.

The base schema is

For what you are trying to do, any transistor, bjt or MOSFET, would work. 2n2222 or 7000 for example. Irf5x0 is actually a poor choice here. It only worked due to the low load being switched.


Set array to array passed as parameter in constructor I have a constructor which looks like this:

Preset::Preset(char* presetName, MIDICommand* MIDICommands[])
  _presetName = presetName;
  _MIDICommands = MIDICommands;
}

_MIDICommnads is declared like this: MIDICommand* _MIDICommands[];.

When run, this throws the error below on the second line in the constructor:

incompatible types in assignment of 'MIDICommand**' to 'MIDICommand* [0]'

Why do I need to declare _MIDICommands as MIDICommands**, and not MIDICommand* _MIDICommands[]?

The array I pass is declared like this:

MIDICommand* one =  new MIDICommand(1, 2);
MIDICommand* two =  new MIDICommand(2, 2);

MIDICommand* MIDICommandsA[] = { one, two };

EDIT:
When I pass in an array, should I just use MIDICommand* MIDICommands, or do I need the [] at the end?
Now I've taken them off, but then I get trouble with passing the array.

It doesn't find a matching function to call. Basically, this MIDICommand* MIDICommandsA[] = { one, two }; doesn't match this MIDICommand* MIDICommands parameter.

EDIT 2:
So, I've solved the problem of passing the array. I changed the parameter in the constructor to MIDICommand** MIDICommands, and I just pass a pointer to the array.

Now the constructor looks like this:

Preset::Preset(char* presetName, MIDICommand** MIDICommands)
{
  Serial.println(MIDICommands[0]->getProgramChange());

  _presetName = presetName;
  _MIDICommands = *MIDICommands;

  Serial.println(_MIDICommands[0]->getProgramChange());
}

I'm getting an error on the second Serial.println, telling me it is a non-pointer type. I'd like it to be a pointer, so that's what I am looking at now.

_MIDICommands is now declared like this: MIDICommand* _MIDICommands.

EDIT 3: When I try to loop through the array now, it seems I have lost the second element, and have only the first.

_MIDICommnads is declared like this: MIDICommand* _MIDICommands[];.

This is the major error. That is an incomplete array type. The number of elements (and storage) is unknown.

To solve this you have decide on how the elements should be stored. Should the class allocate storage and copy the values given to the constructor or should a pointer to the vector be used.

One alternative is to use a template class and provide the max element size as a template class parameter.

Cheers!


File Size Problem with EyeFi SD Card and Arduino Mega I've been writing to an EyeFi SD card with an Arduino Mega.  I've managed to get the files to upload wirelessly, but I noticed that my data gets cut off when the file reaches a size of 24 kb.  If I use a normal SD card, the file is able to keep logging past 24 kb.  The EyeFi card is able to upload large images, so I'm not sure what is limiting my file size for the EyeFi card.  Can I get some advice?

/*************** SETUP ***************/
void setup(void)
{
  Serial.begin(115200);

  // initialize the SD card
  Serial.print("Initializing SD card...");
  pinMode(10, OUTPUT); // make sure that the default chip select pin is set to

  // see if the card is present and can be initialized:
  if (!SD.begin(10,11,12,13))
  {
    error("Card failed, or not present");
  }
  Serial.println("Card initialized");

  // see if the directory exists, create it if not.
  if( !SD.exists(directory) && !SD.mkdir(directory) )
    error("File directory not created");

  newFile();

  Serial1.begin(115200);

  while (Serial1.peek() != '!' )
    Serial1.read();

  i = 0;
}

/*************** MAIN LOOP ***************/
void loop(void)
{
  if (Serial1.available())
  {
    logfile.print( (char)Serial1.read() );
    i++;
  }

  if (i >= SOFT_BUFFER_SIZE)
  {
    logfile.flush();

    if( logfile.size() > 20480 && logfile.size() < (20480 + SOFT_BUFFER_SIZE) )
      Serial.println("Minimum File Size Achieved.");

    i = 0;
  }
}

After some testing and research, I found out that the Eye-Fi SD card starts a transfer once a file reaches 20kb or more and will not upload a file again once it has been transfered already.  The solution, as suggested by ChrisStratton, is to log to a temporary file and trigger a transfer once the file is ready.

I took advantage of the fact that the Eye-Fi only transferring files in the standard camera folders.  In my case, I used the Nikon naming convention: DCIM/100NIKON/DSCNxxxx.JPG  (xxxx is the photo number ranging from 0000 to 9999), but there are also others.  Check on the Eye-Fi website for compatible cameras.  I created a temporary file called TEMP.TMP and stored it to the root folder of the card and logged to it.  Once I'm ready to transfer the file, TEMP.TMP gets renamed to "DCIM/100NIKON/DSCNxxxx.JPG" and the whole file is transferred all at once.

Here's my code.  I'm using the software serial (pins 10, 11, 12, 13) of the Mega:

//Running with 256kb serial buffer (modified HardwareSerial.cpp)
//Added file time stamps

#include "SdFat.h"
#include "SdFatConfig.h"
#include <Wire.h>
#include "RTClib.h"

#define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
uint32_t syncTime = 0; // time of last sync()

#define ECHO_TO_Serial     1 // echo data to Serial port
#define WAIT_TO_START      0 // Wait for Serial input in setup()
#define MESSAGE_SIZE      11 // Message size of "!G N +1234" + CR
#define SOFT_BUFFER_SIZE  256// 25 Messages of 11 chars each

const uint8_t chipSelect = 10;

SdFat sd;
SdFile logfile; //create log file

RTC_DS1307 RTC;
DateTime filedate;

uint16_t date;
uint16_t time;

int i = 0;
int x = 0;

char directory[] = "DCIM/100NIKON";
char filename[] = "DCIM/100NIKON/DSCN0000.JPG";
char tempfile[] = "TEMP.TMP";

/*************** ERROR ***************/
void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);
  while(1);
}

/*********** TEMP FILE CREATION ***********/
void newFileName()
{
  sd.chdir("/"); //check DCIM/100NIKON directory
  // create a temp file
  for (uint16_t i = 0; i < 10000; i++)
  {
    filename[18] = i/1000 + '0';
    filename[19] = (i/100)%10 + '0';
    filename[20] = (i/10)%10 + '0';
    filename[21] = i%10 + '0';
    if (! sd.exists(filename))
    {
      Serial.print("New file name: ");
      Serial.println(filename);
      break;  // leave the loop!
    }
  }
}

/****** call back for file timestamps *****/
void dateTime(uint16_t* date, uint16_t* time) {
  DateTime now = RTC.now();

  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(), now.day());

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}

/*************** SETUP ***************/
void setup(void)
{
  Serial.begin(115200);
  Wire.begin();
  RTC.begin();

  if(! RTC.isrunning() )
    Serial.println("RTC is not running");

  // set date time callback function
  SdFile::dateTimeCallback(dateTime);

  // initialize the SD card
  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (! sd.begin(chipSelect, SPI_HALF_SPEED))
    error("Card failed, or not present");

  Serial.println("Card initialized");

  // see if the directory exists, create it if not.
  sd.chdir("/");
  if( !sd.exists(directory) && !sd.mkdir(directory) )
    error("File directory not created");

  // create new file name
  newFileName();

  // Scan root folder for temp files
  sd.chdir("/");
  while( logfile.openNext(sd.vwd(), O_READ)){
    if( !logfile.isDir() ) {
      logfile.printName(&Serial);
      if( logfile.fileSize() < 20480 ){
        Serial.print(" file size too small. ");
        Serial.print(logfile.fileSize());
        Serial.println(" bytes.");
        logfile.remove(); //Delete under sized files
      }else
        if( !logfile.rename(sd.vwd(), filename))
          error(" could not be renamed.");
        else{
          Serial.print(" renamed to ");
          Serial.println(filename);
        }
    }
    logfile.close();
  }

  // create temp file
  sd.chdir("/");
  if(!logfile.open(tempfile, O_WRITE | O_CREAT)) // only open a new file if it doesn't exist
    error("couldnt create temp file");

  Serial1.begin(115200);

  // Rotate the buffer
  for( int j = 0; j < 256; j++) {
    Serial1.read();
  }

  // Look for the '!' character
  while (Serial1.peek() != '!' )
    Serial1.read();

  Serial.println("Logging...");
  Serial.println();

  // Reset buffer index to 0
  i = 0;
}

/*************** MAIN LOOP ***************/
void loop(void)
{
  if (Serial1.available()){
    logfile.print( (char)Serial1.read() );
    i++;
  }

  if (i >= SOFT_BUFFER_SIZE)
  {
    logfile.sync();
    i = 0;
  }
}


Electronically, should single or several ground pins be used? I have heard two theories of grounding: pretty much ground a board at single point, or ground everything in sight.

With the Mini Pro, is it better to provide one source of ground through the Gnd pin next to the Vraw pin, or ground with multiple Gnd pins on the board?

There are times when you want a single ground point (star grounding), separate grounds with filters (separate analog and digital grounds, for instance), or you just don't care (99% of the time).

Regardless, this is usually a concern when you are laying out a circuit on a PCB. When you already have a PCB the grounds become a moot point because the PCB dictates how they operate.

For a module like an Arduino, unless otherwise stated, all grounds are equal and can be used for whatever whenever.


Arduino library making I make my own library for arduino.

The file structure is like below.

AAA - README.md
    - examples - A - A.ino
               - B - B.ino
    - AAA.h
    - BBB.h
    - CCC.h
    - BBB.cpp
    - CCC.cpp

It works well. But I want to grouping a library source files like below.

AAA - same as above
    - src - AAA.h
          - BBB.h
          - CCC.h
          - BBB.cpp
          - CCC.cpp

It doesn't work at all.

Arduino IDE shows the message

  Specified folder/zip file does not contain a valid library.

But, WiFi101 library was made by src folder. Why isn't it possible for mine?

I'm going to assume your library structure is like this because the structure you described above would not cause that error:

AAA
|_src
    |_AAA.h
    |_BBB.h
    |_CCC.h
    |_BBB.cpp
    |_CCC.cpp

To be considered valid by the Arduino IDE, a library must either have a .h file in the root folder or a library.properties file if you are using the 1.5 library format. Putting all the source files in the src subfolder means your library is in the 1.5 library format. So you need to add a library.properties file in the root of the library formatted as described here: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format. Then your library should look like this:

AAA
|_library.properties
|_src
    |_AAA.h
    |_BBB.h
    |_CCC.h
    |_BBB.cpp
    |_CCC.cpp


arduino on battery for long time use I have a small project with arduino UNO R3 + RTC clock DS3231, that control through a relay a electrovalve (12V).

I would like to use the entire circuit on battery.

The electrovalve (a small motor) has a consumption of 500mA and will be active 4 times a day for 15 second.

I have a 7Ah battery, and I had calculated that my system will work only around 34 hours with it... is there any way to optimize circuit consumption ?

Thanks for any suggestion !

You can turn off the entire Arduino and let it wake by your RTC. That way you can conserve a lot of power. (link)

Also you will have losses from the power regulator when powering the Arduino from 12V. You might consider using a Arduino Pro mini with 3.3V powered by two AA batteries. That should last for years.


3D printer Arduino sketch I'm building an automatic warehouse system using 3 nema17 stepper motor. My problem is to move the motors with precision, since I do not have any kind of encoder on the motor and so I cannot know the position of the axes. I tought that the system could be similar to a 3d printer, since neither 3d printers have encoder on the motor. Where can I find a sketch for Arduino of a 3d printer, to understand how they work? How do they move with such precision without any kind of sensor?

With stepper motors you don't need any form of encoder. Only a limit switch.

A stepper moves in steps - you tell it how many steps to move. As long as you know where you started from (which is what the limit switch is for) then you can always know exactly where you are.

If you told the stepper to move 10 steps clockwise you know the stepper has moved 10 steps clockwise. If you then move 10 steps anti-clockwise, you will be back where you were.

All you need to do is count.


Find a time server for NTP to get the current time (EtherCard library) There are lots of examples around how to connect with an NTP server, but I do not see how to find such an IP-address. From the examples I conclude I need to find it on for example pool.ntp.org, but I do not even see how to get IP-addresses out of there myself, let alone to let my Arduino do it. Of course I looked at the How do I use pool.ntp.org page, but it doesn't seem to say anything about finding IP-addresses.

Questions

  Is it possible to let my Arduino find a working NTP server (using the EtherCard library), and if so, how?
  All the examples I saw have an NTP server IP address hard coded, isn't that a bad practice and also a bad idea for a longer running project?

The code I currently find the easiest to understand is from the Arduino forum, and has an IP address hard coded.

I have an Arduino Nano ATmega328 with a ENC28j60 ethernet shield, and therefore use the EtherCard libray. I do know of existence of RTC devices but I would prefer NTP.

The EtherCard library offers a method called ether.dnsLookup(host) where you ask it to look up the IP address for you.

etherCard.dnsLookup("pool.ntp.org");

...only that might fail, so it returns a false:

if (!etherCard.dnsLookup("pool.ntp.org")) {
    // Error! Do something!
    return;
} // if

But if it works...

if (!etherCard.dnsLookup("pool.ntp.org")) {
    // Error! Do something!
    return;
} // if
// At this stage, dnsLookup() worked...

// Can now connect to IP adress in etherCard.hispip

Now: please note that ntp.org would prefer you to use a more precise locale than pool.ntp.org. If you're going to distribute your application worldwide, then that's fine. But I always use au.pool.ntp.org because I'm in the Australian region. There are others that you can/should use instead.


Change Options for the AVR Programmer via Arduino IDE I want to program an ATtiny through the Arduino IDE. I have a somehow strange programmer. But I can upload via avrdude by

  avrdude -p attiny13 -P /dev/cu.usbmodemfa131     -c stk500v2    -F -B20 -U flash:w:programm.hex

It took a while to figure out that I had to slow the baud rate via the -B20 switch. If I try to upload via the arduino 1.0.5 IDE avrdude is executed as follows.

  /Applications/Adafruit Arduino 1.0.5.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -C/Applications/Adafruit Arduino 1.0.5.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -pattiny13 -cstk500v1 -P/dev/tty.usbmodemfa131 -Uflash:w:/var/folders/9t/5jldfq752fs1x74_rhn2plz80000gn/T/build7680201613426497544.tmp/attinytest.cpp.hex:i

My question is, how can I change the preferences such that I have control over the avrdude parameters? Say I want to add a -B20 switch and change stk500v1 to stk500v2.

Short answer: I'm afraid you can't do it with Arduino IDE 1.0.5.

Long answer:

First of all, be aware that -B20 does not specify the baud rate but the bitclock period (in us); this is specific to stk500v2 programmer.

Normally, enabling your programmer should only be a matter of adding it to the list of programmers known by Arduino IDE; that list can be found in hardware/arduino/programmers.txt. You would then append the following lines at the end of this file:

strangeprogrammer.name=Somehow Strange Programmer
strangeprogrammer.communication=serial
strangeprogrammer.protocol=stk500v2
strangeprogrammer.force=true
strangeprogrammer.speed=?????

However, the problem here is that Arduino IDE does not seem to be able to use flag -B (bitclock period) but only flag -b (baud rate) which value is set to whatever you will put to strangeprogrammer.speed.

At least that's what I could find out by inspecting Arduino IDE source code: AvrdudeUploader.java never adds that flag to the avrdude command-line :-(

That means your options are:

Rebuild the Arduino IDE 1.0 on your own after modifying AvrdudeUploader.java to support -B flag; code should be quite easy (about 2 more lines of Java code).
Switch to Arduino IDE 1.5 and follow Federico's answer :-)
Use another IDE, something that deserves the IDE name. I use Eclipse with this Arduino plugin and it works fine for me. As a bonus, avrdude support seems better as you can see on the screenshot below:


Call function and not came back Im having a little problem with my code. here i called a function to make a test, if it passed it goes back and continue if it doesn't it goes to main loop.

void loop()
{

    if (call == 1)
    {
        funca();
    }
    print("waiting..");
}
 void funca()
    {
        gsmtest();
        print("calling..")
    }
 void gsmtest()
    {
        if (test==1)
             {
            print("test ok");
             }
        else
              {
                print("error");
                loop();
              }
    }

here is a simple example, if u press call, the code goes to funca which make a call to gsmtest. if test goes ok it print "calling.." if not it print "error" and goes back to loop. for some reasons here if test failed, it print error and than goes to loop after that it print "calling.." (continuing funca which i want to abort it if test goes wrong) .

You're overflowing your stack due to infinite recursion.

By explicitly calling loop() you are breaking the whole call stack system. You effectively have:

loop() ->
  funca() ->
    gsmtest() ->
      loop() ->
        funca() ->
          gsmtest() ->
            etc...

Instead of>

loop() ->
    funca() ->
        gsmtest()
    <-
<-

Instead of calling loop() you should use return; to "return" back to where the function was called from.

For example:

void loop() {
    if (call == 1) {
        funca();
    }
    print("waiting..");
}

void funca() {
    if (!gsmtest()) return;
    print("calling..")
}

bool gsmtest() {
    if (test == 1) {
        print("test ok");
    } else {
        print("error");
        return false;
    }
    return true;
}


Arduino ESP8266 receive email? Is there a sketch that supports the receiving of email using the Arduino environment on the ESP8266? I can only find support for sending email. I know it's possible because the NodeMCU environment supports it. Any help is appreciated!

Once you know how to connect to any server and send messages to it, retrieveing emails is just a matter of sending right messages (=commands).

Here below follows an "IMAP tutorial", i.e. guide to which commands to send to an IMAP server to search and retrieve messages.

Note: once you connect to the IMAP server, the first command to send is the login command:

foo login user password

"foo" is just a session identifier, not a keyword. "login" is the keyword.

Once you get the welcome message, you can start sending more commands:

Select the proper folder:

. SELECT "INBOX"

Look for desired message (strings are always considered substrings, so no wildcards are needed):

. SEARCH FROM "user@example.org" SUBJECT "some keywords here"

This will result in list of matching messages, with search results formatted as follows:

* SEARCH 5 10 456

This means messages n.5, n.10 and n.456 match the query.

If examining just the subject (which may contain keywords and switch as required) is not enough, the whole body can be retrieved, both marking the message as read or leaving it untouched:

. FETCH 5  BODY[TEXT]

or

. FETCH 5  BODY[TEXT].PEEK

End IMAP session with:

. logout

For experiments from Windows using telnet:

telnet mailserver.domain.com 143

Reference:

https://www.skytale.net/blog/archives/23-Manual-IMAP.html


Do I need a pull-up/down resistor for button LED circuit? When reading up on how to make a circuit that turns an LED on when a button is held down, I keep finding people saying a pull up or down resistor must be involved, to avoid the flickering state of the LED seen with a floating pin. There's also code being implemented, where the state of a pin is read and monitored as the button is pressed down or left raised. What I don't understand, is why this is all necessary. Surely it isn't, considering the circuit below allows the button to be pressed with the LED turning on/off depending on the state of the button.

I made this circuit before drawing it online, and it works exactly as intended. No need for a pull up/down resistor or any code. I must be missing something here, can anyone please explain? It works perfectly with a buzzer as well.

Many thanks.

The circuit you have made is only using Arduino as a 5V power source. You aren't using any GPIO pins to read the state of the button or to control the LED by an output pin. You've just made a plain-old circuit with a button and LED in series with a power source.

Often for a button-controlling-LED sketch, you will have a button connected between GND and an I/O pin defined as an INPUT_PULLUP, which means the Arduino will be able to read the state of the pin as HIGH (5V) or LOW (0V). The PULLUP part indicates that when the button is not completing the circuit between GND and the pin, a weak voltage is applied to get it up to 5V. In this way it's not "floating" at an unspecified voltage, but is being actively driven to 5V. When you press the button, the input pin is shorted to GND.

A pull-up resistor causes an otherwise un-driven pin to go to logic HIGH. A pull-down resistor causes an otherwise un-driving pin to go to logic LOW.

In the case of a pull-up resistor, reading a logic LOW means the button is pressed, which is kind of the reverse of your circuit operation, so in your sketch code, you would look for LOW to turn on the LED.


Stepper motor won't change directions! I am driving a bipolar stepper motor with an a4988 driver using the AccelStepper library. My goal is to press a button and the motor moves CW, then another button for CCW.
I have looked at another post with a very similar issue, but the solution does not seem to apply well to the AccelStepper library, which I would really like to use given its versatility.
Currently, whichever button I press, the motor moves CCW. Any help would be greatly appreciated!
#include <AccelStepper.h>
AccelStepper stepperX(1, 3, 2);

void setup() {
  pinMode(8, INPUT)
  pinMode(9, INPUT);

  stepperX.setMaxSpeed(100.0);
  stepperX.setAcceleration(100.0);
}

int moveRight = 1000;              //arbitrarily high number
int moveLeft = -1000;              //arbitrarily low number

void loop() {
  while (digitalRead(8) == HIGH) { //when d8 button is pressed move left
    stepperX.moveTo(moveLeft);     //set move
    if (digitalRead(8) == LOW) {   //if not pressed, kill loop
      stepperX.stop();
      break;
    }
    stepperX.run();
  }

  while (digitalRead(9) == HIGH) { //when d9 button is pressed move right
    stepperX.moveTo(moveRight);    //set move
    if (digitalRead(9) == LOW) {   //if not pressed, kill loop
      stepperX.stop();
      break;
    }
    stepperX.run();
  }
}

You work with accelleration and absolute positions. Are you aware of that?
This Library is not made for running permanently in the same direction. It let you define a position where the movement should end, an acceleration or speed and the controller moves the motor to that position.
The run method must be called permanently, It triggers the steps. So, I put it directly into the loop() method.
The following prog should hopefully move the motor towards position 1000 if you press the 8-button, towards position -1000 if you press the 9-button and stops if both buttons are off. I have not the hardware available at the moment, you it's just blind programming. Use it as an idea.
#include <AccelStepper.h>
AccelStepper stepperX(1, 3, 2);

void setup()
{
  pinMode(8, INPUT)
  pinMode(9, INPUT);

  stepperX.setMaxSpeed(100.0);
  stepperX.setAcceleration(3.0);
}

int positivePosition = 1000;
int negativePosition = -1000;

void loop()
{
  if ( digitalRead(8) == HIGH )
  {
    stepperX.moveTo(positivePosition);
  }
  else if (digitalRead(9) == HIGH)
  {
    stepperX.moveTo(negativePosition);
  }
  else
  {
    stepperX.stop();
  }
  stepperX.run();
}


Using TMRpcm library, the audio does not play I'm using the https://github.com/TMRh20/TMRpcm/wiki library to play wav files from an SD card to a speaker I have attached to my Arduino.

I have run separate tests/programs that ensures:

my speaker is connected properly and can play sound
my SD file is connected properly as it can read and files, text files.

However, I'm trying to use the tmrpcm.play("example.wav") command and nothing is happening. I used wav files that for sure works (from a demo I found online) so it's not the wav file problem.

Anyone have any clue on what is going on and how I can fix this?

This is now 5 months later - but I recently had the same problem.

Because the TMRpcm library plays through pulse width modulation, make sure your speakers are hooked up to a PWM capable pin.

That caused me no end of headaches trying to figure out.


Problem with serial connection. Data garbled I have a hardware device that sends data over the serial port and over a socket connection.

I have the TX of the device connected to the RX of the ESP8266, RX of the device to TX of the ESP8266.

Comm speed is set to 115200 on both.

Code is nothing more than

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
}

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

I listen on the socket and on the serial port at the same time. On the socket port i get correct data (ASCII characters). On the serial monitor of the Arduino i get garbled data. Also, it looks like the Arduino IDE cannot cope with the volume of data. I am sending appx 100 char/sec.

Any ideas?

Update Aug 13 '18

Ok, I found out that I was trying to hook up an RS232 to an UART and that, to accomplish this, I need a RS232 to TTL converter like the max3232. I will go that road and update the question if I have it.

Ok, i found out that i was trying to hook up an RS232 to an UART and that, to accomplish this, i need a RS232 to TTL converter like the max3232.
I will go that road and update the question if i have it.

I think RS232 signals are outside the TTL limits; I don't know if you've done any permanent damage.

On the interfacing itself:

https://www.sparkfun.com/tutorials/215

On the damage part:

https://forum.arduino.cc/index.php?topic=26139.0


How much current can arduino ground absorb? I am currently working on an LED 4x4 cube, so here is my pre planned circuit diagram.
https://easyeda.com/editor-mobile/#id=ffca9f3303f242a185b950b0bee4fa29|

I am to connect 220ohm to each positive terminals.(16)

I am to use 4 transistors(2n2222) for 4 negative layers of which, collector terminal will be connected to the negative terminal layers , base will be connected to 4 analog pins through 1k ohm, and emitter to be connected to the GND pin of arduino. Using transistor as a switch.

Can my studio ground get damaged if connected directly without a resistor.
If no?
Is there any way to make it?
Explanation with circuit diagram will highly be preferred...
Thanks for your precious time...

No your gnd won't get damaged if you source current through it. If u need explanation let me know


Timer frequency calculation for UNO/Atmega328 I must be overwrought or something... I just can't get the calculation of the timer frequency right. I have a 16 MHz crystal on the Atmega328. I want 1 kHz timer interrupt rate. So I chose prescaler = 64 and counter top = 249, that is

fTimer = fCPU/prescaler/(top+1) = 16 MHz/64/250 = 1 kHz

But my oscilloscope shows 2 kHz... !? Why?

I have read Timer2 Compare Interrupt not working as expected but the accepted answer doesn't make it better. There the frequency is half as high whereas mine is twice as high as expected.

Code:

const int signalLED = 1; //14;

void setup()
{
  pinMode(signalLED, OUTPUT);
  digitalWrite(signalLED, LOW);

  TCCR2A = 0; // set TCCR2A register to 0
  TCCR2B = 0; // set TCCR2B register to 0
  TCNT2  = 0; // reset counter
  OCR2A = 249; // top value in CTC mode
  TCCR2A |= (1 << WGM21); // enable timer2 CTC mode
  TCCR2B |= (1 << CS21) | (1 << CS20); // 1:64 prescaling for timer 2
  TIMSK2 |= (1 << OCIE2A); // enable timer2 compare interrupt
  sei(); // allow interrupts
}

ISR(TIMER2_COMPA_vect)
{
  // generate peak
  digitalWrite(signalLED, HIGH);
  digitalWrite(signalLED, LOW);
}

void loop()
{
}

Your comment:

TCCR2B |= (1 << CS21) | (1 << CS20); // 1:64 prescaling for timer 2

doesn't match the actual setting (= 1/32)

Also there are some issues with setting Timer2 CTC mode, it's better to set mode, then OCR2A + TCNT2 + interrupts and then Prescaler to start the timer. It behaves as there is OCR2A=0, so the frequency is much higher than expected.


LED strip brightness decreases when using multiple strips Newbie question here.

I have bought a 5V, 40A power supply to externally power up some LED strips (WS2812B). The Arduino Nano is powered by a standard USB wall charger (5V).
So far I have tested with 4 LED strips (each of about 25 LED's). Each of the strips is connected to an individual data pin on the Arduino in addition to the power supply (5V and ground).

So, to the problem. For each LED strip that gets powered it seems that the brightness of the LED's decreases. Using for example "white color", all the LED's shows a "yellow"-ish color when all the LED strips are powered. If only one or two is powered it looks fine.
The Arduino by the way shares the same ground as the power supply.
What could the cause to this issue be? The power supple should be more than sufficient for the task. Is it the data pins that can't handle it?

Thanks for any help!

EDIT:

I more detail, each LED strip has 3 pins (1 for 5V, 1 for data input, and 1 for ground). Each for the LED strips 5V pin are connected to the + rail on a breadboard where the power supplies + is also connected. The same goes for the ground pin of the LED strips (they are connected to a ground rail on the same breadboard where also the ground of the power supply is connected).
The data pin on the LED strips are connected to 4 (when all are connected) different data pins on the Arduino Nano (A1,A2,A3 and A4).

The ground pin on the Arduino Nano is connected to the same breadboard ground rail as the rest. When I didn't do this the LED's had weird behaviour.
The wires going from the LED strips into the breadboard are standard 24 AWG stranded wires (each of about 50 - 80 cm in length).

Power supply used is "AC 110V-220V TO DC 5V 40A" from ebay.
https://www.ebay.com/itm/AC-110V-220V-TO-DC-5V-12V-24V-Switch-Power-Supply-Driver-Adapter-LED-Strip-Light/152134115704

LED strips that are used "5M WS2812B 5050 RGB, 150LEDS ip65 Waterproof"
https://www.ebay.com/itm/5M-WS2812B-Strip-LED-Lights-5050-RGB-30-60-LED-M-IC-Individual-Addressable-DC5V/113117301639?

40 amps is a LOT of current.

24 AWG wire can't handle anywhere near 20A of current, nevermind 40A. (After a little googling, it looks like 24 AWG wire is limited to about 3.5A.)

Think about it. In the US, 15 amp branch circuits require 14 AWG wire. 20 amp circuits require 12 AWG wire. It looks like 40 amps requires 8 AWG, from the googling I did. (Voltage doesn't really matter when considering current carrying capacity.) So if you want to drive 40 amps, you need 8-gauge wire on both the +5 leg and the ground leg to your LED strip.

As I said in my comment, I found some 144 WS2812B LED strips on Amazon that draw 20A just for one strip. You say your strips have 150 WS2812B LEDs on them. Assuming it's 150 vs 144 of the same LEDS, you're going to need almost 21 amps per strip, so 2 strips will slightly exceed the 40A capacity of your power supply, and VASTLY exceed the current handling ability of your wiring. As a general rule you should have a power supply that offers a little MORE current that your max needs, never less.(When a power supply reaches its current limits its voltage may start to droop, or it may be slower to adjust to rapid changes in load.)

In addition, You're gonna need BIG, THICK 5V and ground wires to feed your LED strips, and you should wire the LED stips in parallel. (I suggest 8 AWG wires for 40A. Those are HUGE, but that's what you need for that much current.) You should not connect either the +5V supply or the ground wires through a breadboard.


What's the maximum number of keys in Yun Bridge? The Yun has a Bridge for communicating between the Arduino and Linux processors via a key/value hash. The docs say this is actually stored on the Linux side, but it doesn't say what the limit is.

How many key/value pairs can the Bridge store? What are the practical limitations?

The data is just stored in an array within the Python daemon. The ATMega32U4 just sends commands to set / get the values, so there is no limit imposed by the ATMega side of things.

The only limit is the size of the array in Python, and that is restricted by:

The amount of available memory in Linux, and
Whether or not you have swap space set up on the Yun

Since both those are very much variable (it depends what processes you have running, what your configuration is, etc) the answer can only really be:

Quite a few.

Putting memory aside for a moment, an answer to this question on SO states:

  According to the source code, the maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*) . On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912. Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements.

So you have the smaller of:

The maximum you can fit in Linux's memory, and
536,870,912


What is the call to cli(); routine in interrupt service routine for SPI? I see this in examples of ISR code but what is it?

Interrupts are normally turned off automatically when an ISR is called.

There are two instructions that allow software to turn off (cli) and on (sei) interrupts to create a sequence of non-interruptable instructions, i.e. an atomic operation or critical section.

In some MCU there are several levels of interrupt priority and an ISR with lower priority may be interrupted by an ISR with higher priority. An atomic operation may also be required in an ISR with lower priority.

There are also cases where an ISR may allow interrupts (with the same or lower priority) to occur after the critical section of the ISR.

Normally an ISR should not contain cli()-sei() especially for the AVR. The hardware will automatically turn off interrupts during the execution of the ISR.

Cheers!


Sensors go crazy on external power For few days, I am trying to figure out, why my sensors do not work on external power. I bought NodeMCU along with couple different sensors etc. I was happily working with them, connecting them one by one to the 3.3v pin in the NodeMCU board, programming each of them. Everything was working as expected. After I have finished, I decided it's time to use them all at once, but I knew, that for that to work, I need to provide them with enough power, as USB probably won't be enough (plus, when I'm done, I don't plan to use USB to power the system anyway). I have a module that converts 230v AC into 5v DC, and then I am stepping it down to 3.3v in order to power the sensors. After checking with multimeter, the voltages are ok, and so is the current.

My problem is, that the sensors give completely random data (most of the time they don't give any information, but once in a while they send something like 1000 times the normal value). Below you can see the schematic that I use. Can you please help me figure this out?

Edit: I would just like to add - I did try to run NodeMCU solely on the Ext. Power - the circuit looked exactly as below, I just connected positive output of 3.3v power source, to the 3.3v connector on NodeMCU. The board was working (I was able to control the onboard LED via WiFI), but the sensor did not. I then reconnected the sensor from external power, to NodeMcu 3.3v, and it (the sensor) worked... I have no idea why.

simulate this circuit – Schematic created using CircuitLab

Sorry I don't have reputation for a comment but this might be of help.

You didn't specify if the sensor was a breakout board. If it is then the board may already have the resistor in place, which is why removing it worked.

Now if you had the resistor in place when it was also connected to the nodeMCU, then perhaps power from it was high enough to still generate a stable operating condition (not familiar with nodeMCU) but more likely you have a power supply issue.

Is it a module and does it have resistor on board.
was the 27k resistor only in circuit on external power.

If the answer was yes to the above that is probably the issue.

If they are not the cause, my next check would be your external power. It could need calibration, power spikes/ripples etc but the easiest thing to do is put in a smoothing capacitor in circuit after your power supply.

Probably about 20-30% of my sensor issues are resolved by this. Another 60% are solved by fixing my screw ups and assumptions.


How do I properly trigger the ATMega328 reset pin via software so that the bootloader runs and the firmware can be updated via RX/TX pins? I am programming my Atmega328P chip via a USB to TTL converter (https://www.amazon.com/gp/product/B075N82CDL/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1)

I am able to upload hex files via the command line and the Arduino IDE when I have the RTS pin of the adapter and a capacitor attached to the !RESET pin of the Atmega. (http://www.electronics-lab.com/wp-content/uploads/2018/09/programming-Uno-on-breadboard.png)

I am also able to upload via the command line when I have a push button attached to the !RESET pin and manually pull it low then begin uploading the firmware within a few moments. (https://cdn.instructables.com/F0L/2F6U/J7AQSHD1/F0L2F6UJ7AQSHD1.LARGE.jpg)

My problem is that for my application I will only have the TX/RX/Vcc/GND pins available (no RTS or push button) and need to reset the micro controller so the bootloader runs and listens to be programmed with updated firmware.

So far I have written a batch file that sends a command to restart the Arduino, and then calls avrdude to upload a hex file. I have tried two methods of restarting the micro controller. I have told it to go to memory location zero, and I have attached an IO pin to the reset and dropped it low (although it stays low until reset, so the reset doesn't really work until I manually remove the wire between the IO pin and the !RESET pin)

My sequence is as follows:

Have Arduino running code:

    int recvByte;
    int delayS = 400;
    int resetPin = 9; //bttom right pin of uC

    void setup() {
      // put your setup code here, to run once:
    pinMode(txPin, OUTPUT);
    pinMode(rxPin, INPUT);
    pinMode(resetPin, OUTPUT);
    digitalWrite(resetPin, HIGH);
    Serial.begin(57600);
    Serial.write("Booted/reset");
    Serial.write("This setup was uploaded with batch");
    }

    void(* resetFunc) (void) = 0;

    void loop() {

    if (Serial.available() )
    {    // get incoming byte:
        recvByte = Serial.read();
        if (recvByte==int('r'))
        {
        Serial.write("resetting");
        delay(10); //wait for last message to send
        //digitalWrite(resetPin, LOW); //commented out because this method stays low until wire is removed
        resetFunc();
        Serial.write("should not see if reset properly");
        }

    }

    delay(100);
    }

2.I then run my batch file.

echo Running upload bat, sending reset command then calling avrdude
cd "C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\"
python "path\sendR.py"
.\avrdude.exe -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -carduino -PCOM6 -b57600 -D -Uflash:w:"path\Atmega328code.hex":i

The python sendR.py is to send the "r" character, which the Arduino views as the reset command.

import serial
ser = serial.Serial("COM6", baudrate=57600)  # open serial port
bytes = "r".encode()
ser.write(bytes)
ser.close()
print("End python script")

When I send "r" via Tera Term or python the setup code runs again, but I have not been able to upload with the .\avrdude.exe -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -carduino -PCOM6 -b57600 -D -Uflash:w:"path\Atmega328code.hex":i command inside the batch file. If I use the pushbutton to do a hardware reset, this command works without issue.

How can I upload new firmware via the RX and TX pins using software to reset the microcontroller and listen for new code as the bootloader runs?

New ideas tried:
Use a uniform baud rate of 57600 in python and atmega serial setup. I chose this value because the Arduino IDE output this baudrate in avrdude.exe -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -carduino -PCOM6 -b57600 -D -Uflash:w:"path\Atmega328code.hex":i

You wrote:

  void(* resetFunc) (void) = 0;

This seems to me like an approach worth trying, except that the function
address is wrong. At address zero of the flash you have the start of the
user's code. The bootloader, if you do use one, lives at the end of the
flash. The start address of the bootloader depends on its size, and is
configured by setting some fuses on the chip. If you are using the
popular optiboot (the bootloader of the Uno), you have to jump to
exactly 512 bytes before the end of the flash, i.e.:

void (*resetFunc)(void) = 0x7e00;

Oh, wait... the flash is organized as 16-bit words, so you may have to
use the wordwise address instead:

void (*resetFunc)(void) = 0x3f00;

But do note that, unlike a real hardware reset, this approach does not
reset the peripherals to their normal initial state. You may want to do
it before jumping to the bootloader.

Edit: I have disassembled a test program that does this kind of
call-by-pointer, then double checked the documentation of the icall
instruction. It appears that the function address you provide is
indeed interpreted as a word-wise address, so you should write half the
byte-wise address. If you write anything larger than the size of the
flash (0x4000 = 16 kilowords), the most significant bits get
lost, and the address gets reduced to the correct range modulo the flash
size.

That is, if 0x7800 worked for you, then presumably the correct address
is 0x3800, i.e. 2 kilowords (4 KB) before the end of the
flash. This is quite a large bootloader, and the largest size supported
by the ATmega328P. Are you sure it is righ? Aren't you sliding through
some uninitialized flash before hitting the bootloader? Here is a table
that gives the bootloader's start address as a function of the amount of
memory reserved for it:

reserved size  start address
    512 B         0x3f00
     1 KB         0x3e00
     2 KB         0x3c00
     4 KB         0x3800

Note that the Arduino Uno uses optiboot, which fits into the
smallest size that can be allocated to a bootloader (512 bytes).


Arduino and ESP8266 Web server First things first, if there was an ESP8266 StackExchange, I would post this there.

I am setting up a web server that will programmaticly be controlled from an external Python script, and I am currently able to send this server data using this script, but I don't receive an HTTP response back when I do, so the external script crashes.

I have googled around and not found much on this, so the question is How do I, From the Arduino, using an ESP8266 send an HTML response code?

After countless Trial/error attempts, I was able to put together the proper sequence.

AT+CIPSEND=0,40  \\Set this for your current connection ID and payload length.
HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n
AT+CIPCLOSE=0  \\Set this for your current connection ID

Send these commands with the arduino, and it should exit successfully.  You can also flush out the HTTP line with any other information you would like to include, as defined in the rfc2616 (HTTP/1.1) standard


Need some help on a very small project Apologies for the simple question, I really couldn’t find any help online with this as when I kept searching, the results had lights that had way too much voltage compared to what I need.

So I have a simple light decoration that requires around 3v and comes with a battery pack to power it (2AA batteries) and I took it apart and was able to connect them via a breadboard to test if is all working.

How do incorporate the Arduino into it so that I can switch the lights on through the Arduino? A lot of the small voltage videos I saw were just simple connecting 1 LED through a digital pin but that’s not enough current for the lights I have and I’m not experienced enough to find myself a solution so help would be greatly appreciated.

For little more info, the 3.3v and 5v pins my Arduino (uno) are already taken up.

Also, I’ll be turning the lights on and off with an IR Remote which I’ve already programmed to a servo that’s powered through the USB supply (5v) and the IR Sensor is connected to the 3.3V.

Sorry if the question was badly worded.

I think I managed to make a little circuit that should prevent you from burning up your Arduino.

From what I read you shouldn't connect MOSFET directly to Arduino. Imagine that MOSFET has a little capacitor inside it, and in the beginning that capacitor can take such high current that actually can burn the Arduino pin. Instead you use a simple NPN transistor (with 100kohm resistor) as a "switch". The NPN can survive much higher current, and it will not strain the Arduino pin.

When I simulated this setup using the default "blink" sketch the light bulb was lit when PIN13 was HIGH. Just note that there always is a small voltage drop (think of it as a resistor inside the MOSFET) and it can make the MOSFET get a little warm. In your setup it should not be a problem, but in some cases it's nice to screw a radiator on the MOSFET.


Sensing concentration of methane with MQ-4 methane sensor? I'm on a project to sense any amounts of methane in the home. I have bought the popular MQ-4 methane sensor from SparkFun: https://www.sparkfun.com/products/9404

I've looked online for any sample code, but I am confused as to whether the input from the sensor is already given in parts per million, or it is just a voltage. To be specific, here is the sample code the data sheet for the sensor gives:

int sensorValue;

void setup()
{
  Serial.begin(9600);      // sets the serial port to 9600
}

void loop()
{
  sensorValue = analogRead(0);       // read analog input pin 0
  Serial.println(sensorValue, DEC);  // prints the value read
  delay(100);                        // wait 100ms for next reading
}

I have also used a breakout board for these sensors: https://www.pololu.com/product/1479
The sensor is soldered on it, along with a 20K ohm load resistor, like how the spec. sheet specifies.
However, I am confused on the readings I am getting. It's always something that ranges between 259 and 261. Is this ppm of methane in my home? If it is, shouldn't the normal level be 0? I currently have no methane based heating. Or is the 259 - 261 voltage?

Thanks for any help.

Actually, you are getting raw data from the sensor. A little bit of math should be done in order to calibrate it and based on the chart in datasheet, measure the real value in PPM.

The calibration basically helps you find R0, which is an internal resistance (along with RS form a voltage divider) that could be derived by doing calibration in a clean environment. After that, you use R0 to calculate a ratio and then look at the datasheet's chart to measure whatever gas you want since there is a curve describing it.

Please refer to this tutorial for more information. I have developed a similar application using MQ-4 before.

It is related to MQ-2, you may have noticed that all theses sensors have similar features and principle applications.


exit(0) function shows up an error So I have been trying to write a code where I use the millis() function to print the milliseconds of on-time of the board using Serial. But the condition is I want to stop printing the value once it reaches 10 seconds (10000ms).

I have been trying to use the exit() function but I get no output then.

#include<stdlib.h>

void setup()
{

  Serial.begin(9600);          //  setup serial

}

void loop()

{

unsigned long timer1;

while(timer1%10000!=0)

{

timer1=millis();

Serial.println(timer1);

}

    exit(1);

}

The AVR library documentation for exit() is great help. It explains that the interrupts are turned off and an infinite loop is entered. As the interrupts get turned off the last characters in the Serial buffer are not transmitted.

You can use Serial.flush() to wait for the transmission to complete before calling exit().

Cheers!


WebSocket client for ArduinoHttpClient conditional if with readString() incoming data buffer I'm having issues implementing a web socket on the Arduino/Genuino to procress a string received and do something respectively.

I'm using SimpleWebSocket example, edited for my purpose, from the ArduinoHttpClient...

don't seam to get the hangs of it. don't know what i'm doing wrong, cannot store the received string object on a string variable or use the readString() method on and if statement to compare with a string to decide what flow path to get in to

This is the code im trying:

/*
  Simple WebSocket client for ArduinoHttpClient library
  Connects to the WebSocket server, and sends a hello
  message every 5 seconds

  note: WiFi SSID and password are stored in config.h file.
  If it is not present, add a new tab, call it "config.h"
  and add the following variables:
  char ssid[] = "ssid";     //  your network SSID (name)
  char pass[] = "password"; // your network password

  created 28 Jun 2016
  by Sandeep Mistry

  this example is in the public domain
*/
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "config.h"

char serverAddress[] = "192.168.1.140";  // server address
int port = 8000;

WiFiClient wifi;
WebSocketClient client = WebSocketClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;
int count = 0;

void setup() {
  pinMode(6, OUTPUT);

  Serial.begin(9600);
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);                   // print the network name (SSID);

    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);
  }

  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
}

void loop() {
  Serial.println("starting WebSocket client");
  client.begin();

  while (client.connected()) {
    int messageSize = client.parseMessage();

    if (messageSize > 0) {
      String test = client.readString();
      Serial.println(client.readString());
      Serial.println(test);
      if (client.readString() == "off") {
        Serial.println("low");
        digitalWrite(6, LOW);
      }
      else {
        Serial.println("high");
        digitalWrite(6, HIGH);
      }
    }
  }

  Serial.println("disconnected");
}

On the example above, you can see in the void loop, after I check there's incoming data with messsageSize I store the incoming data using readString on a variable test, which I then println, this shows and empty line, although when I directly via println readString it shows some data, so the data is coming in... subsequently when I try to use the data from the incoming buffer on and if statement to compare with a string is wont work.

I've tried everything I can think off, puting the string to compare in to a variable and compare them, using Compare method from the object and I cannot even remember what else.

does anyone have any advice on how to do this, maybe the library is buggie, maybe I'm doing it wrong, any other libraries that anyone can recommend, I've looked around and this is the only one that looked simple enough to get started with and had the most examples.

this workes:

if (messageSize > 0) {
      //Serial.println(client.readString());
      String input = client.readString();
      Serial.println(input);

looks like reading from the method readString() empties the buffer hence cant use it again, what I did is store it on a String object variable "input" and use that.

It worked.


What is the memory expense of creating a String from a char array? I'm writing a little API for processing email messages in Arduinos. Obviously, I need to keep memory use down, but I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.

My logic uses char arrays (so that memory is statically allocated). If my end user converts a char array to a String (so that they can easily see if an email subject startsWith() a particular word) will this result in doubling the character memory used? .. or will the String class simply include a pointer to the original char array (and just add some cruft)?

What would be the best-practice in this kind of situation?

What would be the best-practice in this kind of situation?

To not use String.

I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.

There's nothing wrong with providing an indexOf function in your API.  But you don't have to use String to implement that function when called.  You can just use the strstr function on char arrays (reference here).
I should also point out that most Arduinos do not have enough RAM for storing an email.
UPDATE 07-01-2016:
To answer the titular question, the fixed cost of using String is at least 1600 bytes of program space, more if you use more than a few methods.  The linker can throw out methods you don't use.
Then for each String variable you declare, the recurring cost is 8 bytes for the variable itself, plus the variable-size memory chunk for your character data.  This chunk is allocated from the heap, and is the size of your string plus 4 more bytes to manage the chunk within the heap.  That's a total of 12 extra bytes per String instance.
However, I did not originally answer that question because you explicitly asked about the memory expense.  This ignores other expenses that should not be ignored:

execution time - Allocating memory from the heap is really a search for a chunk of the requested size.  At the beginning it can be quick, but as the heap gets fragmented (small chunks build up) it takes longer to find a chunk.  And when the String is emptied or destroyed, the memory chunk gets put back into the heap and (possibly) merged with adjacent chunks.  Reducing the size of a String does not free up any memory.  The String maintains its maximum size until it is emptied or destroyed.
long-term stability - Embedded Systems are supposed run forever.  A primary characteristic of a system that can run forever is "deterministic."  For whatever inputs it receives, it has a predictable response and end state.  When you use the heap via String, the heap gets fragmented according to the data it handles.  This is not predictable, and it may get into a state where no memory chunk of the requested size is available.  Choke.
maintenance - because the heap state depends on the processed String data, finding the cause of the failure can be difficult.  It can fail at different times because the input data is different, and it can fail at different places in the program.

Because of these expenses, String is rarely used by an experienced developer.  Unfortunately, String is tempting to the beginner because it is easy to understand.  What is difficult to understand is the complicated, non-deterministic behaviour under the hood that inevitably leads to system failure, rending of garments and gnashing of teeth.


Can't send HTTP request using ESP8266 and Arduino Uno I have an Arduino Uno and for Wifi an ESP8266.

My ESP8266 Firmware is

AT+GMR

AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04

baund = 115200,
 Both NL & CR

Server -- www.linysoft.com

The URL I want to send is either: http://www.linysoft.com/arduino/?light=off OR http://www.linysoft.com/arduino/?light=on.

Depending on to the link I send the result should be either ==> on or ==> off on the page http://www.linysoft.com/arduino/light.json.

Now I want to send an HTTP request (Weblink - http://www.linysoft.com/arduino/?light=on) so it can write according to that link "on" in the light.json page.

The AT command I am sending (my wifi module is connected to my wifi automatically):

WIFI CONNECTED
WIFI GOT IP

AT+CWMODE=1

OK

AT+CIPMUX=1

OK

AT+CIPSTART=0,"TCP","www.linysoft.com",80

0,CONNECT

OK

AT+CIPSEND=0,200

OK
>

Here I am getting a problem after this > I can't send **GET /arduino/?light=on**. I also tried GET /arduino/?light=on HTTP/1.0\r\n.

After putting this line in the textbox, I press the Enter button or Send Button, but nothing happens.

It is stuck here > for some time. And then it shows me:

OK
> 0,CLOSED

Pin Connection

ARDUINO UNO        ESP8266
RX  -------------->  TX
TX  --------------> RX
VCC--------------> 3.3
CH_PD ----------> 3.3
GND -------------> GND

The domain is missing. Try this instead:

GET http://www.linysoft.com/arduino/?light=on HTTP/1.0\r\n\r\n

Cheers!

Ref. http://contractorwolf.com/esp8266-wifi-arduino-micro/


Send stepper to position and back AccelStepper At the moment I am working on a code that should send a plateau to a certain position and back. The plateau is being moved by the stepper, in my case a Nema 17 with a Polulu DRV8825 driver. Everything is hooked up correctly.
My goal is to press '4' on the keyboard and that then the stepper moves to a certain position. However, I am not succeeding in this. I am using AccelStepper and at the moment I have the following code:

#include <AccelStepper.h>

AccelStepper stepper(1, 5, 4);

int spd = 1000;    // The current speed in steps/second
int sign = 1;      // Either 1, 0 or -1
int buttonState = 0;

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(1000);
  stepper.setSpeed(1000);
}

void loop()
{
  char c;
  if (Serial.available()) {
    c = Serial.read();
    if (c == 'f') {  // forward
      sign = 1;
    }
    if (c == 'r') {  // reverse
      sign = -1;
    }
    if (c == 's') {  // stop
      sign = 0;
    }
    if (c == '1') {  // super slow
      spd = 100;
    }
    if (c == '2') {  // medium
      spd = 900;
    }
    if (c == '3') {  // fast
      spd = 1000;
    }
    if (c == '4') {
      //not working, does anyone know how to do this?
      stepper.moveTo(500);
    }
    stepper.setSpeed(sign * spd);
  }
  stepper.runSpeed();
}

Does anyone have tips or know how to achieve this?

Thanks is advance!

Gerben's comment:

  You need to call stepper.run() instead of runSpeed, for moveTo to work.

provides the answer. The updated code is:

#include <AccelStepper.h>

AccelStepper stepper(1, 5, 4);

int spd = 1000;    // The current speed in steps/second
int sign = 1;      // Either 1, 0 or -1

int buttonState = 0;

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(1000);
  stepper.setSpeed(1000);
}

void loop()
{
  char c;
  if (Serial.available()) {
    c = Serial.read();
    if (c == 'f') {  // forward
      sign = 1;
    }
    if (c == 'r') {  // reverse
      sign = -1;
    }
    if (c == 's') {  // stop
      sign = 0;
    }
    if (c == '1') {  // super slow
      spd = 100;
    }
    if (c == '2') {  // medium
      spd = 900;
    }
    if (c == '3') {  // fast
      spd = 1000;
    }
    if (c == '4') {
      //not working, does anyone know how to do this?
      stepper.moveTo(500);
    }
    stepper.setSpeed(sign * spd);
  }
  stepper.run(); //You need to call stepper.run() instead of runSpeed, for moveTo to work. – Gerben
}


Arduino only addresses 3 LED at a time I am running the following sketch on an Arduino Uno using Arduino 1.6.8.
Strip is a WS2811 12V.

#include <Adafruit_NeoPixel.h>
#define PIN 6
Adafruit_NeoPixel strip = Adafruit_NeoPixel(30, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show();
}

void loop (){
   strip.setPixelColor(0, 255, 0, 255);
   strip.show();
}

The problem is that the LED’s light in (Green) groups of three and what I want is individual control.

strip.setPixelColor(0, 255, 0, 255); Illuminates Pixels 0,1,2
strip.setPixelColor(1, 255, 0, 255); Illuminates Pixels 3,4,5
strip.setPixelColor(2, 255, 0, 255); Illuminates Pixels 6,7,8

And so forth.

Although this code uses NeoPixel I get exactly the same issue if I use the equivalent in FastLed.

Any pointers to what I am doing wrong would be appreciated.

LED strips with WS2811 and 12V are the ones with one driver and 3 RGB LEDs on it. These are interconnected so you just can't control less than whole group of three.

If you need individual control, you have to get 5V variant with WS2812.


Sending Serial Hex Command from Pin 1 (Tx) Using Arduino Uno with 3.5mm Jack connected to ground and pin 1 for TX

Need to send two commands
I want to send
0XAA13FE010113 for Mute on, and
0XAA13FE010012 for Mute off.

Simple Serial Command to turn Monitor Mute on and off every 5 seconds....

tried everything byte character, array, write with hex, print :(

Thx for a helping a rookie
I want to impress my team

Ideal quick answer below. thx to @martynas

uint8_t muteON[] = { 0xAA, 0x13, 0xFE, 0x01, 0x01, 0x13 };
uint8_t muteOFF[] = { 0xAA, 0x13, 0xFE, 0x01, 0x00, 0x12 };
....
void loop() {
 Serial.write( muteON, sizeof(muteON) );
 delay(5000);               // wait for 5 second
 Serial.write( muteOFF, sizeof(muteOFF) );
 delay(5000);               // wait for 5 second
}

there are 6 bytes just make

byte muteON[] = {0xAA,0x13,0xFE,0x01,0x01,0x13};
byte muteOFF[] = {0XAA,0x13,0xFE,0x01,0x00,0x12};
...
/* To send mute ON comand */
for(byte i =0;i<sizeof(muteON);i++)(Serial.write(muteON[i]));
/* To send mute OFF comand */
for(byte i =0;i<sizeof(muteOFF);i++)(Serial.write(muteOFF[i]));


Problem with a DHT11 Temperature & Humidity sensor I'm new in the Arduino world and today i was trying to make a simple program to show the temparature an humidity with this sensor. I made a circuit following one tutorial and nothing happend, the result was Temperature: 0 Humidity: 0.
My question is, what is wrong? Probably the sensor is broken or the code is wrong.
I also need to say that i use a 5K1 resistor in exchange of the 4.7K resistor and accidentally I connected the sensor without the resistance for a few seconds.

This is the code:

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

int SENSOR = 2;
int TEMPERATURE;
int HUMIDITY;

DHT dht(SENSOR, DHT11);

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

void loop() {
TEMPERATURE = dht.readTemperature();
HUMIDITY = dht.readHumidity();
Serial.print("Temperature: ");
Serial.print(TEMPERATURE);
Serial.print(" Humidity: ");
Serial.println(HUMIDITY);
delay(1000);
}

This is the circuit scheme:

This is a photo of the circuit and the sensor (probably damaged):

Thanks for your time and sorry for my bad english.

Finally I was able to solve the problem by not using the resistor and connecting it directly, I also had a problem with the sensor pins since some were badly connected, but it was also solved. Now both sensors are working well including the melted one. Thanks!.


Connecting arduino to a PC How would you send data wirelessly from arduino uno to a pc?

I know you can connect wifi shield / wifi breakout to arduino and use that, but what other ways are there and how practical would they be?

You have several options. One is Bluetooth and another is nRF24L01+ 2.4GHz Wireless Transceiver. I love the nRF24L01+. They are cheap and there are tons of examples online.

The concept with the nRF24L01+ is to connect the RF24 to a Ft232rl Ftdi Usb to Ttl Serial Adapter. The Ft232rl  connects to your PC. Most modern computer languages support communicating via Serial. This is the way to go.

Google around for a ton of tutorials


Stepper Motor Power Supply Just a quick question. Picking up some stepper motors, but confused at what voltage/current things are running off.

Ordering:
2 x Stepper Motor
2 x EasyDriver

An article says

  You need some 12V source to the EasyDriver (the motor in this article
  is 12V) - This will be powering the stepper - Im using a 12V adapter -
  similar to the one in the illustration. Just make sure it is rated at
  least 750ma - A higher rating is better, and just means it wont burn
  out.

So does that mean if I got a plug which is regulated 12V 1A and powered the Arduino from that I could power a rail with VIN pin and that would safely supply the EasyDrivers? And I could then use the 5V pin to power everything else?

Just don't want to break anything! Thanks

Stepper Motor Control - one step at a time

This program drives a unipolar or bipolar stepper motor.
The motor is attached to digital pins 8 - 11 of the Arduino.

The motor will step one step at a time, very slowly. You can use this to test that you've got the four wires of your stepper wired to the correct pins. If wired correctly, all steps should be in the same direction.

Use this also to count the number of steps per revolution of your motor, if you don't know it. Then plug that number into the oneRevolution example to see if you got it right.

#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0;         // number of steps the motor has taken

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

void loop() {
    // step one step:
    myStepper.step(1);
    Serial.print("steps:");
    Serial.println(stepCount);
    stepCount++;
    delay(500);
}