text:
Arduino GSM module + SMS string sending garbage value
I want to check the water level and have an SMS sent via a GSM module. Reed switches are connected to four Arduino analog inputs.
I am unable to add a string and tank level (TKLVL) in program.
The program is sending some garbage value via SMS. But TKLVL variable prints the right value.
What is wrong with my code?
    #include <SoftwareSerial.h>
    SoftwareSerial SIM900(10, 11);
    String textMessage;
    #define LED1 2
    #define IRLED 3
    //#define rf433DATA 4
    //D4 IS CONNECTED TO RF433MHZ RECEIVER CHANGE ACC TO LIBRARY
    #define PIRpower 5
    int receiver = 6;
    #define VALVE1 7
    #define GSMRESET 8
    #define pumpONdetect 9
    #define VALVE2 12
    //#define TANK_SENSPOWER 13 //
    #define TANK_SENS4 A0  //full tank wigh buzzer
    #define TANK_SENS3 A1
    #define TANK_SENS2 A2
    #define TANK_SENS1 A3  //low tank
    int TKLVL= 0;
    int LEVEL;

    void setup()
    { pinMode(LED1, OUTPUT);
      pinMode(IRLED, OUTPUT);
      pinMode(PIRpower, OUTPUT);
      //CHECK RECEIVER PIN
      pinMode(GSMRESET, OUTPUT);
      pinMode(VALVE2, OUTPUT);
      // pinMode(TANK_SENSPOWER, OUTPUT); //DRIVE THIS PIN LOW TO ON TANK POWER(PNP TRANSISTOR)
      pinMode(TANK_SENS4, INPUT); //FULL TANK WITH BEEP BUZZER
      pinMode(TANK_SENS3, INPUT);
      pinMode(TANK_SENS2, INPUT);
      pinMode(TANK_SENS1, INPUT); //LOW TANK WATER
      // digitalWrite(TANK_SENSPOWER, HIGH); //turns OFF tanksenspower OFFvia PNP transistor..
      Serial.begin(9600);
      SIM900.begin(9600);
      Serial.print("SIM900 ready...");
      SIM900.println("AT+CMGD=1,4\r");
      delay(1000);
      // AT command to set SIM900 to SMS mode
      SIM900.println("AT+CMGF=1\r");
      delay(400);
      // Set module to send SMS data to serial out upon receipt
      SIM900.println("AT+CNMI=2,2,0,0,0\r");
      delay(400);
      digitalWrite(VALVE1, LOW);

    }

    void loop()
    {
      if (SIM900.available() > 0) {
        textMessage = SIM900.readString();
        Serial.print(textMessage);
        delay(10);
      }
      if (textMessage.indexOf("Von") >= 0)
      {
        G_valve1On();
        Serial.println("on loop");
        textMessage = "";
      }
      if (textMessage.indexOf("Voff") >= 0)
      {
        G_valve1Off();
        Serial.println("off loop");
        textMessage = "";
      }

      if (textMessage.indexOf("Tanklvl") >= 0)
      {
        Tanklvl_calc();
         Serial.print("TKLVL is=");
         Serial.println(TKLVL);
        //  TKLVL=LEVEL;
        // Serial.print("level is=");
        //Serial.println(LEVEL);
        String msg ="TANK IS " + TKLVL;
        Serial.println(msg);
        sendSMS(msg);
        textMessage = "";
      }

    }
    //SEND SMS function
    void sendSMS(String lvlmsg)
    {
      SIM900.print("AT+CMGF=1\r");
      delay(1000);
      SIM900.println("AT+CMGS=\"+9182375*****\"\r");
      delay(100);
      SIM900.println(lvlmsg);
      delay(100);
      SIM900.println((char)26);
      delay(1000);
      SIM900.println();
      delay(5000);
    }

    void G_valve1On()
    {
      digitalWrite(VALVE1, HIGH);
      Serial.println("...turning valve1 on...");
    }
    void G_valve1Off()
    {
      digitalWrite(VALVE1, LOW);
      Serial.println("...turningvalve1 off...");
    }

    int Tanklvl_calc()
    {
      if (digitalRead(TANK_SENS4) == HIGH)
      {
        TKLVL = 100;
        Serial.println("TANK LEVEL 100%");
      }
      else if (digitalRead(TANK_SENS3) == HIGH)
      {
        TKLVL = 75;
        Serial.println("TANL LEVEL 75%");
      }
      else if (digitalRead(TANK_SENS2) == HIGH)
      {
        TKLVL = 50;
        Serial.println("TANK LEVEL 50%");
      }
      else if (digitalRead(TANK_SENS1) == HIGH)
      {
        TKLVL = 25;
        Serial.println("TANK LEVEL 25%");
      }
      else
      {
        TKLVL = 0;
        Serial.println("TANK LEVEL IS LESS THAN 25%");
      }
      return(TKLVL);
    }

Are you receiving some sms from UNO ? Did serial monitor print correct value?

Garbage values received in sms

@MITURAJ  plz chk string msg command,I think it nor combining statement +level variable.

Serial.println(msg); <-- Did this work? I doubt if it prints junk value cz TKLVL is int type. Convert it to string using --->
String msg = "TANK IS " + String(TKLVL)

@MITURAJ No this line doesnt print any value.

Try
String msg = "TANK IS " + String(TKLVL)

String msg= "led is" + ledstate this line works.but ledstate is boolean variable.

Any other way by which I can send tank level variable valve as sms??

if (textMessage.indexOf("Tanklvl") >= 0) <--- sms is sent ONLY if this condition is satisfied. Did you check if this worked first ?

Yes I ve checked this condition.

String msg = "TANK IS " + String(TKLVL) <-- did this work?

Step by step: send hardcoded string in SMS. If the SMS is OK->problem came for the way you build the msg. If the SMS is wrong-> problem came from the sending. Notice one detail: seems you can't send all kind of character in SMS. I've made Android App exchanging SMS and I' ve had to avoid some char which were received as garbage.

Using Strings in a microcontroller is a no-no.
First, try to send a test SMS, to see if everything works OK on SIM800-Arduino etc.
If you receive it correctly, then try to play with char arrays.
First, declare a char array big enough for your data to fit in. Let's use a demo array, but keep in mind that it's your responsibility to keep things tidy.
byte sizeOfBuffer = 10;
char smsString[sizeOfBuffer] = {'\0'};

What we did is create an smsString array of 10 bytes, 9 bytes for data and 1 byte for our special end of sting character. Since we don't want Arduino to handle things with Strings, we have to tell our microcontroller where does that String end. That's what '\0' does.
Then, modify the send function to accept that data type.
//SEND SMS function with char array
void send_SMS_charArray(char *lvlmsg, byte sizeOfsms)
{
  SIM900.print("AT+CMGF=1\r");
  delay(1000);
  SIM900.println("AT+CMGS=\"+918237504767\"\r");
  delay(100);
  for (byte i=0; i<sizeof(sizeOfsms); i++){
    SIM900.print(lvlmsg[i]);
  }
  Serial.println();
  delay(100);
  SIM900.println((char)26);
  delay(1000);
  SIM900.println();
  delay(5000);
}

Finally, to call the new function you would do something like
sprintf_P(smsString, PSTR("TANK IS: %i"), TKLVL);
send_SMS_charArray(smsString, sizeOfBuffer);

Notice sprintf_P when using static messages such as "TANK IS". It will save your life in a few months.

TKLVL is integer type. Convert it to String object and add :-
String msg = "TANK IS " + String(TKLVL)


text:
Storage usage of methods compared to copied code
When you have really small snippets of code that are repeated several times in your micro controller program, is it better to write a method? I mean better in terms of performance and storage usage. I know that when programming for PC, code repetition is a big no go, but what about micro controllers?
In the following example (Arduino Nano with Adafruit 2,8" cap touch display) the snippet should look if the back button is pressed in several screens. I checked in the Arduino IDE how much storage each version takes:
Version 1, 15114 Bytes for complete program:
void battScreen(TS_Point p){
  // some other code
  // ....
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

void alarmScreen(TS_Point p){
  // some other code
  //...
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

void pumpScreen(TS_Point p){
  // some other code
  // ...
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

Version 2, 15234 Bytes for complete program:
void checkBack(TS_Point p){
  if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
    if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
      screen = MAIN1;
      showMainScreen();
    }
  }
}

void battScreen(TS_Point p){
  // some other code
  // ...
  checkBack(p);
}

void alarmScreen(TS_Point p){
  // some other code
  // ...
  checkBack(p);
}

void pumpScreen(TS_Point p){
  // some other code
  // ...
  checkBack(p);
}

As you can see, version 2 with the extra method takes 120 Bytes more storage. Is there a rule of thumb when it makes sense to create a new method instead of copying code?

Maybe the following question also gives you some insight: https://stackoverflow.com/questions/144993/how-much-overhead-is-there-in-calling-a-function-in-c

Your comparison is quite strange; functions take LESS space than copying code. I'll try implementing it, since I think there is some other issue with your specific code

Also (except for the interesting result), not to optomize if it is not needed. Mostly readability, maintainability favors above performance or used flash memory.

@frarugi87 This is possible, although I just changed the code as in the question. Maybe (part of) the reason is what Code Gorilla wrote in his answer with copying variables.

It.... depends
A call to function involves a few things

Save the context
Move the parameter(s) to the appropriate registers
Enter the function
Execute
Eventually save the return value to a register
Restore the context
Eventually copy the returned value to the variable

As you can see, quite a lot of things. The bold points are the ones executed also if you don't use a function.
Please note that if these functions are "methods", you have also a "hidden" parameter (the object you are applying the method onto)
So why use functions? Well, you will have to write this code in flash only once instead of more times.
What is best? It depends on your application.

You are calling this function only once? Don't use a function
Your function is really short (for instance, a one-liner)*? Don't use a function
You are running out of flash memory? Use a function
You need a lot of speed? Don't use a function (you add overhead)
You are not in one of the previous cases? Do as you prefer

With one-liner I mean something like, for instance, byte sum(byte a, byte b) { return a + b; }; in this case the function also occupies more space, since the call function instruction is compatible with the byte sum

Please note that usually more readability is more important than performances, so maybe using functions should be encouraged. I mean, in your case I'd probably use them unless there is a problem
What to do if you don't want to use a function? Well, there are other techniques:

Mark the function as inline; this is a hint for the compiler not to create a function but to replicate this every time. This is only a hint, so the compiler may ignore this
Instead of a function write a macro. This will be substituted every time, but the code will be maintainable. As a drawback, it is much harder to debug with the usual methods.

Just a remark: usually smart compilers can guess what is the best option (inline or function) on their own also for non-inline functions. So you can also trust the compiler in 90% of the cases

You haven't mentioned optimization: if you use a function only once the compiler will most likely just place the code inline, thus avoiding the overhead of a function. You can also force a function to be inline, so you have the convenience of no duplicate code coupled with the efficience of inline code.

The optimization is in the last remark; I could have highlighted it more. Moreover how can you force the compiler to inline? I thought that the "inline" keyword was just a hint; is there another keyword to force the inlining?

__attribute__((always_inline)).

The reason I would tend towards the second method more is there is less opportunity for bugs in the second version.
If storage size is a major concern and you know that repeating the code requires less storage, then I would #define it as a macro and get the best of both worlds.
You could improve the code though.  At the moment you are passing copies of the variable into functions, passing const references might use less room, void checkBack(const TS_Point& p){

using void checkBack(const TS_Point& p) indeed reduced the size by 80 Bytes. Thank you for that!

What seems strange though, is that const type& variable  only reduces size with the TS_Point variables, not with int, uint16_t or other normal types, where it increases size. I know this is not the question, but do you know the reason for that?

source: Stack Exchange

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

sort: votes


text:
Trigger external interrupt on Arduino Uno R3 with an LED and a button
I want to cause the external interrupt on digital pin 2 (PD2 on ATmega328). I have chosen any logic change mode. Here is my code:
void setup()
{
    DDRD &= ~( 1 << DDD2 );//PD2 on input mode
    EICRA |= ( 1 << ISC00 );//any logic change
    PORTD |= ( 1 << PORTD2 );//pull-up enable
    EIMSK |= ( 1 << INT0 );//turns on INT0

    DDRD |= ( 1 << DDD5 );//PD5 on output mode
    PORTD |= ( 1 << PORTD5 );//turn on PD5

    SREG |= ( 1 << 7 );//global interrupts enabled
}

void loop()
{

}

ISR( INT0_vect )
{
    if( ( PIND & ( 1 << PIND5 ) ) > 0 )//if turned on
    {
         PORTD &= ~( 1 << PORTD5 );//turn off led
    }
    //and vice-versa
    else
    {
         PORTD |= ( 1 << PORTD5 );
    }
}

Here is how I connect things.
NOTE: I did not find an ordinary button which just connects two contacts ( which I actually use ). Here if I understand correctly the button in the picture connects left pair and right pair of contacts so everything is connected when pushed and disconnects them from each other when released.

The problem is when I push the button no interrupt occurs. What am I doing wrong?

If the button isn't pressed, the pin is floating, reacting to all electrical things near it. You habe to usw the resistor as pullup or pulldown. That might be the problem. Google pullup resistor and find a tutorial about it

As I know ATmega328 already has pull-up resistors. That is why I turn it on by specifying appropriate bit in PORTD register.

But your fritzing shows, that the button is connected to 3.3V, not to ground. And when you are using the internal pullup, you don't need another resistor

And your code doesn't compile, because in the ISR you try writing to register PIND5, which is only a pin, not a register. You have to write to PIND. Also in your last statement you have an extra parenthesis.

The setup function is only run once. You get no speed gain by writing directly to registers in the setup function. The gcc compiler has "_BV()" and Arduino has "bit()" to select a bit. You don't use both. The Arduino also enables the global interrupt. You can make it yourself easier with the Arduino functions, and only optimize the ISR if you have to.

@chrisl, Those are typos. Thank you for noticing. Edited. But why should I write it to PIND not a PORTD? Your typo?

Pin 2 is pulled up by internal R then pulled up when button is pressed?
Connect button to GND.

OMG. I did not understand correctly what pull-up means. Thank you all. Now it works.

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


text:
How to Identify pins connected to each other?
There is probably another way to achieve what I want without connecting pins to each other, so I will explain the scenario:
I am trying to build an Arduino based Enigma Machine. The cryptography is working fine, it runs from the serial monitor. Now I want to make the interface more real.
The original machine has a plugboard: 26 terminals (labeled from A to Z) where you can connect a cable from one letter to another, and the user can make up to 10 of these connections.
I am stuck in this part. How could I do it electronically? How to tell the microcontroller if a pin is connected to any other pin?
If I assign each terminal to a separated pin on the board, I can't have these pins in output and input mode at the same time.
My first idea was to make an array of resistors to make uniques associations and read the different analog values, but it is impractical.
I also tried to draw a logic circuit to read exact associations, but also doesn't work.
I know it can be done with an Arduino Mega, as there are replicas being sold online based on this board. Is there any other hardware suitable for the situation? I wiil be glad to hear.

How to tell to the microcontroller if a pin is conected to any other pin? ... you don't have to tell it anything ... the microcontroller can detect connections between pins

I cant have these pins in output and input mode at same time ... just set only one as output

If you have enough pins for all 26 terminals, you can directly through all connection iteratively:

Set all pins to INPUT_PULLUP
Set one pin to OUTPUT and LOW
Read all pins beside that one output pin and check, if one reads LOW (meaning connection between output pin and this one)
Repeat for all pins (each pin being an output pin in one iteration)

You could save this in an array of 26 ints. The position in the array would be the "start pin" of the connection, the value would be the target pin.
With the above algorithm you of course get each connection twice. Either just ignore the second one in whatever you are doing with the data, or you can check, if that pin already got a connection and set it's value to -1 (meaning "not important/not needed").
If you don't have enough pins, you can use a multiplexer, where you can connect multiple terminals to one pin on the Arduino, one at a time, iterating again over very terminal.

I think it is useful having at position X mapping to Y and at position Y mapping to X

Thanks for the answer, but this way is also impractical, as it has to work in a real machine.
For example, if I grab a cable and connect one end on the pin 1, and then I grab another cable and connect to the pin 2, I will have two loose ends. If I connect the first end of the first cable on the pin3, in this moment the Arduino wouldnt be able to know if the connection is 1-3 or 2-3.

@DiegoDyan yes, it would know, that the connection is between pin1 and pin3, since that connection would result in a pulled to LOW pin 1 and pin 3. The other cable does nothing, since it is connected only at one side, which is electrically the same as connecting nothing in this case. So in your scenario the second cable (which is connected only on one side) could just as well not be there. Only the connection, that forms a circuit (by connecting two pins) is relevant. So I don't see, where the problem would be.

I think you are right. In my head, the trigger to start the iteration would be the first connection, but not necessarily is.
I simulated it with less pins in ThinkerCad and it kind of works. The code needs some fine tuning to return the exact parameter, but the answer is useful. Thank you very much.

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


text:
Basic WiFly server returning unexpected output within web client
Currently trying to implement a lightweight webserver using the WiFly shield and an Arduino UNO, this is the code I have so far:
#include <SPI.h>
#include <WiFly.h>
WiFlyServer server(80);

/* Function defs */
void cmd(void)  { SpiSerial.print("$$$"); }
void dhcp(void) { SpiSerial.println("SET IP DHCP 0"); }
void pass(void) { SpiSerial.println("SET WLAN PHRASE 22222222"); }
void ssid(void) { SpiSerial.println("JOIN BTHOMEHUB"); }
void port(void) { SpiSerial.println("SET IP LOCAL 80"); }
void ip(void)   { SpiSerial.println("SET IP ADDRESS 192.168.1.123"); }
void tcp(void)  { SpiSerial.println("SET IP PROTOCOL 2"); }
void boot(void) { SpiSerial.println("REBOOT"); }

/* Pointer to a handler function */
typedef void (*Handler)(void);
Handler table[8] = { cmd, dhcp, pass, ssid, port, ip, tcp, boot };

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

  for(short x = 0; x < 7; x++) {
    table[x]();
    delay(100);
  }
}

void loop() {
  WiFlyClient client = server.available();

  if(client){
    while(client.connected()) {
      if(client.available()) {
        client.println("
Hi

This is text.
");
      }
    }
    delay(100);
    client.flush();
    client.stop();
  }
}

This compiles well, but when hitting 192.168.1.123 in my web browser I get an ever-increasing output like:
*HELLO*<
<
<
<
<
<
<
<
<
<
<
< (cont.)

Definitely not the expected html. I have been playing with this code for hours now and this is the most positive output I can get. If I do a Serial.write(client.read()) within if(client.available()) { I am able to print all the request information to the serial monitor, it just seems I am perhaps sending the data in an incorrect format? Any suggestions? Cheers
Edit
I have updated the codebase to include the http headers,
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println("");
client.println("<!DOCTYPE html>");
client.println("
Hi.....

now I get I different (similar) output, seems like it is printing the first character of each new line
*HELLO*H
C
C

<
<
H
C
C

A web server sends more than just HTML. It sends all the HTTP headers as well, which you seem to be missing.

@Majenko Added the http headers, check the edit

You still aren't outputting it right. There has to be a single blank line between the headers and the body to separate them.

@Majenko check now

Your browser sent a HTTP GET request. You need to send a HTTP response in kind, in accordance with the protocol, for your browser to correctly interpret the data. Something like this should do:
  #define TIMEOUT 100
  char response[] = "
Hi

This is text.
";
  unsigned long lastRead;
  ...

  while (client.connected()){
    if (client.available()){
      lastRead = millis();
      while (millis() - lastRead < TIMEOUT){
        while (client.available()){
          Serial.write(client.read());
          lastRead = millis();
        }
      }
      client.println("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: closed\r\n\r\n");
      client.print(response);
      break;
    }
  }
  delay(1000);
  client.stop();

EDIT:
It turns out that the Wifly shield sends a response status as well as "HELLO" by default. You have to disable that with a few commands:
set comm remote 0
set comm open 0
set comm close 0

This will ensure that "HELLO" isnt sent each time a client connection is made, though I'm not sure if this affects the default HTTP/0.9 200 OK response status that is always sent. You can try the sketch above with and without the response header to see what you get.

Hey, appreciate your answer -- I tried this but my browser just hangs

Weird, so with client.println("<!DOCTYPE html>"); I get a response, but again it looks like: `HELLOH
S
C5
C
<
<H
S
C5
C`

the serial monitor looks good: GET / HTTP/1.1 Host: 192.168.1.123 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8  but the browser still hangs

With the timer it seems to hang regardless of the <!DOCTYPE html>, and yeah the browser renders the html fine :j

@WilliamPaul How about this? I changed the timeout and the print()s

Okay, so the timer still causes the browser to hang, but without that and with the updated http header I get: *HELLO*S H <H <H <H <H <H (more than one char on a line)

@WilliamPaul I've edited the answer


text:
How to Implement Simple, Quick HMAC on Arduino
Hi I am a research student working on securing the communications in Controlled Area Networks (CANs), and I am using Arduinos to simulate one of these CANs.
My goal is to use HMAC to implement message authentication of packets, and the algorithm must be very fast (I was originally thinking of using FNV1a). However, there are no Arduino libraries for this (I found one, but it uses SHA which will most likely be too slow for CAN). I don't have a lot of practice with cryptography and hash algorithms, only usage of them.
So basically, I need help writing a FNV or FNV1a function in C. The message for input will be a key (obviously) concatenated with a string (char array). Also, I need the hash to be between 128 and 256 bits for sufficient security.
Just as a side note: A CAN message/packet looks like 7df#02010d and the actual data part, 010d (two bytes) is the char array I will be using. For example, as integers, the array for 010d would be {1, 13}.
--
I also know this message applies more to cryptography than Arduino, but I figured someone from this community might have more experience with my particular task, or even have/know of a library I can use that I hadn't found.
-Thanks

EDIT: I found this FNV1a implementation in C/C++ that might work. But I have not tested it yet.

HMAC = Hash-based Message Authentication Code

I ended finding a Arduino library called Spritz which can be found here:
https://github.com/abderraouf-adjal/ArduinoSpritzCipher
Also, for anyone else who comes across this task, here is a very simple Hashed Message Authentication Code (HMAC) example I scrapped together:
https://github.com/zach-king/ArduinoStash/blob/master/src/Spritz_HMAC/Spritz_HMAC.ino
This library supports encryption as well, which is nice, but not needed in my case.
--EDIT--
The SpritzCipher library was actually too slow (about a 50% reduction in network speed) so I must try a different approach. I have found a MD5 library for Arduino which I will try next:
https://github.com/tzikis/ArduinoMD5

How did ArduinoMD5 implementation go?

@mixdev It's been a couple of years now so I don't remember the exact details of the performance, but I believe I did end up going with the MD5 implementation. MD5 was sufficient for speed and bit-length security for my purposes.


text:
NeoPixel Blink/Glitch
I'm having this weird effect where my NeoPixel will blink/glitch after every cycle of a fading sketch. I'm not certain whether the issue is hardware or in my code. The blinking only occurs during the if statement portion of the code and not during the else statement which blinks red. I have tried multiple sources of power, 5V 2amp, 9V 1 amp, 12V 1amp and a Mac Usb and the problem persists on each power supply.
Any suggestions or ideas would be greatly appreciated.
#include <Adafruit_NeoPixel.h>
#include <DistanceGP2Y0A21YK.h>

#define PIN 6
#define PIXEL 16

Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL, PIN, NEO_GRBW + NEO_KHZ800);

DistanceGP2Y0A21YK Dist;
int distance;
int R = 0;
int G = 0;
int B = 0;

void setup() {
  strip.begin();
  strip.show();
  strip.setBrightness(127);

  Serial.begin(9600);
  Dist.begin(A0);
}

void loop() {
  distance = Dist.getDistanceCentimeter();
  Serial.print("\nDistance in centimers: ");
  Serial.print(distance);
  delay(2); //make it readable

  if (distance > 10) {

    for (R && G && B; R < 150 && G < 150 && B < 150; R++ && G++ && B++) {
      for (int i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, strip.Color(R, G, B));
        strip.show();
        delay(1);
      }
      delay(2);
    }

    // fade off
    for (R && G && B; R > -1 && G > -1 && B > -1; R-- && G-- && B--) {
      for (int j = 0; j < strip.numPixels(); j++) {
        strip.setPixelColor(j, strip.Color(R, G, B));
        strip.show();
        delay(1);
      }
      delay(1);
    }

  } else {

    for (int j = 0; j < 256; j++) {
      for (int i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, strip.Color(255, 0, 0));
        strip.show();
      }
      delay (1);

      //blink off
      for (int j = 64; j > 0; j--) {
        for (int i = 0; i < strip.numPixels(); i++) {
          strip.setPixelColor(i, strip.Color(j, 0, 0));
          strip.show();
        }
        delay (2);
      }
    }
  }
}

Pick a brace style and stick with it. You'll find that other people can read your code that way.

for (int j = 0; j < 256; j++) {

  ...

  //blink off
  for (int j = 64; j > 0; j--) {
    ...

Notice that you are re-declaring the variable j.

Thanks for all the responses however I diagnosed the problem and figured out the fix. The problem comes from my for loop where I use a boolean expression for (R && G && B;. Rather the values should be initialized to 0 and look like  for (R = G = B = 0;


text:
Arduino Yun, node.js and serial
I'm trying to bypass Bridge library and read serial directly from nodejs. I'm on the last sys upgrade (1.3) I have correctly installed nodes and serial module via opkg install. I have also commented out the line in the /etc/inittab:
#ttyATH0::askfirst:/bin/ash --login

This is my arduino code:
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("dudee");
  delay(100);
}

This is my node.js code:
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyATH0", {
    baudrate: 9600,
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    flowControl: false
}, false);

console.log("hello");

serialPort.on("open", function () {
    console.log('open');
    serialPort.on('data', function(data) {
        console.log('data received: ' + data);
    });
});

serialPort.on('error', function(err) {
    console.log('error: '+err);
});

serialPort.open();

If I ssh to yun and run the script I don't see any "dudee":
~/test# node serial.js
hello
open

While if I open the serial monitor I see it.
If I run the node script on my computer (changing the right serial port name) everything works nice and I see the dude..
What can it be?

Autosolved thanks to this old forum post.
It is Serial1 not Serial.
In the Arduino code in the Yun Serial is a different object from Serial1. Even if it is not super well document (or at least not in the first dumb google search) here are some links that talks about Serial1:
https://www.arduino.cc/en/Tutorial/YunSerialTerminal
http://andrea-toscano.com/arduino-yun-tcpip-to-serial1-redirect/
http://crossbar.io/iotcookbook/Arduino-Yun-Disable-Bridge/

Thanks man, this was really helpfull, as I had the same issue.

@nkint would you like to elaborate how did the post help you? Your answer would be good for other seekers.

@ChetanBhargava: it is only a different object in the arduino side.. Serial is different from Serial1 int he Yun..


text:
Arduino DUE and optocoupler 4N25
I'm using an Arduino Due board with an optocoupler 4N25 to simulate a button pressed.
I have to open and close a circuit that drive an actuator. In that circuit, when connected, with the tester I'm measuring 6V.
I connect the anode to the pin 12 and the cathode in series with a 150-ohm resistor to ground, and Collector and Emitter from optocopupler to the circuit (and a normal Blink example with the pin 12).
When optocoupler is fired on and off respectively with a tester I measure 0V and 1.7V in the arduino part, and 4V and 6V.
This is not enough and the actuator is always run. I'd like to read 0-6V instad of 4V-6V. Does this depends on how much current goes to the anode/cathode of the optocoupler? Do I have to change the resistor in the arduino part? Any kind of advice? What can I do?
I don't want to use relay because I have read that in respect to a relay they are faster, smaller, longer-lived and quieter.

Could you add a circuit diagram to your question? It might help people understand the problem better.

@PeterR.Bloomfield : ok, see the edit please

The connection to the Arduino looks OK I think. It could be a problem with how you're trying to use the optocoupler. Could you expand the diagram to show exactly how your actuator circuit is connected (including its power source and ground)?

it is a black box I cannot open sorry. I don't know anything else then the voltage when the button is pressed

I think I can act on the resistence on the arduino side to change the voltage.. am I wrong?

Since it doesn't reach 0v it means the photo-transistor isn't saturated. Try using a lower value resistor (e.g. 80Ohms). But my guess is the external actuator circuit is just connected wrong. This optocouple can sink only 50mA.

@nkint The resistance on the Arduino side only affects the LED inside the optocoupler. The correct resistor value depends on the voltage you're supplying to it.

It sounds like the 4N25 opto-coupler on its own can't do what you need because it's not designed to directly make/break a connection between a power source and its load (i.e. it isn't functionally equivalent to a relay).
Internally, the switching functionality is provided by an NPN photo-transistor. A typical open collector usage would be something like this:

(Image copyright Lewis Loflin: http://www.bristolwatch.com/ele/opto_isolated.htm)
The switch (S1) and the power source (Vi) on the left would be your Arduino. All the connections on the right would be part of your device (the actuator).
As you can see, you need 3 connections on the right: voltage source (Vcc), ground, and the output (Vo, which goes to your device). The circuit basically works by pulling the output (Vo) either up to Vcc to turn it on, or down to ground to turn it off.
It looks like all you have is Vcc and Vo, so this kind of configuration won't work. (Don't try to use the ground from your Arduino instead. That could cause various other problems.)
It should be possible to setup additional circuitry to act more like a Solid State Relay, but without a ground reference point it can be harder than it sounds. A mechanical relay might be the easiest option.

Hi! Thank you for your clear response. I have ho simulate a "press a button" functionality. I have only the 2 wire that goes in and out from the button. Don't know what else can I try to do, I can not open the device (it is under warranty). And I cannot use a Solid State Relay (it make a little "tick" when fired, and everything is for a small concert room: the silence is high priority, we already tried that, does not work). Do you have any advice?

From you clear answer I understand that 4N25 is a Phototransistor opto-isolators and not simply a Opto-isolator as I thought. Can a simple Opto-isolator can be a better solution? In case, can you advice me a model that is good with the Arduino Due?

(I have used a relay like this one: http://store.arduino.cc/product/T010010 and it does not work, too noisy for my porpoise)

@nkint It's a mechanical relay which makes a tick. A Solid State Relay (SSR) is purely electronic; it has no moving parts so it makes no noise. (Some of them even have built-in opto-couplers.) A photo-transistor is very common in opto-couplers, but there are certainly other designs. I can't recommend anything specific, but you might get some good suggestions on a more general electronics site, such as http://electronics.stackexchange.com

If he's replacing a SPST switch in common usage, the opto-isolator will be perfectly satisfactory, as long as it's wired up with the more positive switch terminal on the collector. The transistor will replicate the same behaviour as the switch: either open circuit, or connecting the two pins.


text:
Blend Micro uploading sketch
I have just got the Blend Micro board.
After following the getting started tutorial I can't manage to upload sketches on the board. Now, in Arduino v. 1.0.6 I see the voices

Blend
Blend Micro 3.3V/8Mhz
Blend Micro 3.3V/16Mhz (Overclock) as in this picture:

While the L Led is switch on if I upload the sketch the TX and RX leds stay off. The modified Arduino IDE says "Done uploading". As port I choose /dev/tty.Bluetooth-Serial-1 and I don't see any other port and I think this is critical.
But if I open the Android BLE application BLE Controller, after tried to upload the BLEControllerSketch (from RBL_nRF8001 libraries) it finds the board but print the error No Response from the BLE Controller sketch. If I try with SimpleChat example and the SimpleChat Android application if finds the board but prints only "Hello World" and nothing else if I send strings from the android app.
Any kind of advice?
EDIT
I am on a Mac 1.8.5. I have tried also with Codebender, but anything change: I can't see the /dev/tty.usb* in the listed ports

Did you follow the setup exactly? In particular, did you modify main.cpp to have this:
#if defined(BLEND_MICRO_8MHZ)
    // As the F_CPU = 8000000UL, the USB core make the PLLCSR = 0x02
    // But the external xtal is 16000000Hz, so correct it here.
    PLLCSR |= 0x10;             // Need 16 MHz xtal
    while (!(PLLCSR & (1<<PLOCK)));     // wait for lock pll
#elif defined(BLEND_MICRO_16MHZ)
    // The CPU clock in bootloader is 8MHz, change to 16MHz for sketches to run (i.e. overclock running at 3.3v).
    CLKPR = 0x80;
    CLKPR = 0;
#endif

If not, what happens is once the sketch starts the USB stops working and you can't see the serial port due to the clock speed being incorrect. This is why you can only see /dev/tty.Bluetooth-Serial-1 in the port list.

Modify main.cpp according to http://redbearlab.com/getting-started-blendmicro
Press the reset button on the Blend Micro, then quickly select Tools -> Serial Port in the Arduino IDE. The Blend Micro serial port should be there because the boot loader is still running. It will be named like /dev/tty.usb????????
Select that serial port. Compile your code. Now press reset at the same time as pressing upload. Your sketch will upload and the serial port should now be present when the sketch is running.

Update: The Timing Tricks
Note: Blend Micro is basically the same as Arduino Leonardo.
This is the timing:

The reset button is pressed.
The ATMega32u4 restarts. It jumps to the bootstrap loader code.
The bootstrap loader starts up the USB as a CDC device (serial port) and waits for firmware upload instructions. (Pulsing L LED)
If no upload instructions are received within a certain time (8 seconds?), it jumps to the application code.
The application code starts up the USB as a CDC device again.However, since the oscillator (clock) on the Blend Micro is different to the Leonardo, it requires the modifications above, otherwise the USB clock will wrong, and the USB won't work.

If the modifications above were not done, Step 3 is the only time when the USB is working and the serial port can be selected in the Arduino software.

yes I have replaced the correct arduino.cpp. so you can confirm that the rx and tx should blink during upload and the /dev/tty.usb* has to be in the list. ok.. can you explain me what happens during the black magic of pressing the button and suddenly click in the button? I will try this evening

so you are saying me that if I press the reset button and the L led is fading (and the boot loader isn't still running) I should see the /dev/tty.usb* listed in the available ports.. This does not happens. I also tried to ls /dev/tty.* just in case does not refresh so quickly and nothing new appears..

Ok it works! but please explain me the timing tricks!

@nkint please see edits

For anyone else who is having an issue with this. What worked for me, was replacing the cable with a shorter cable. I could of been using a charging only usb cable or the cable was long enough to not upload correctly.


text:
arduino pro mini fqbn
Introduction
I am trying to program an arduino pro mini, I have to use this board because of it's size.
I use the arduino-cli to program arduino and one of the steps to upload code to the system requires the board's fqbn and I can't find it anywhere.
Question
Does anybody know this board's fqbn (fully-qualified board name)?

https://github.com/arduino/ArduinoCore-avr/blob/1.6.21/boards.txt#L670-#L697

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


text:
Using AysncUDPMessage for ESP32 to send string data
I am in search for some examples as to how can one use the AsyncUDPMessage in an Application for sending out UDP packets to a host with specific IP address and Port number from an ESP-WROOM-32 (Olimex ESP32-PoE) module?
The Class for AsyncUDPMessage in arduino-esp32 library inherits from Print.
I want to send sensor measurements to InfluxDB in the Line Protocol (InfluxDB specific).
Example
 imu,location=front,nodeid=node1 status=0.00,liac_x=-1.18,liac_y=0.02,liac_z=9.63,eul_x=0.00,eul_y=-6.81,eul_z=0.25 1538507409930

The above mentioned example is stored in the form of a String and the methods to send information via UDP viz. send() sendTo() all mention usage of AsyncUDPMessage as the first parameter.
goal
Send the above measurement to the particular Device's IP and port
udp.sendTo(Message, IPAddress(192,168,3,11), 8089);

I am currently using broadcastTo(const char * data, port) menthod to send information the InfluxDB instance.
Code
void loop(void) {

  DateTime now_time = rtc.now();

 // create a measurement
  influxMeasurement row("imu");
  row.addTag("location", "front");
  row.addTag("nodeid", "node1");

// get information from BNO055
  imu::Vector<3> li_ac = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);
  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);
//  Serial.print(li_ac.x());
//  Serial.print(li_ac.y());
  row.addField("status", 0);
  row.addField("liac_x", li_ac.x());
  row.addField("liac_y", li_ac.y());
  row.addField("liac_z", li_ac.z());
  row.addField("eul_x", euler.x());
  row.addField("eul_y", euler.y());
  row.addField("eul_z", euler.z());

  // add timestamp
  row.addTimeStamp_ms(String(now_time.unixtime()) + String(millis()%1000));

  // print the Line Protocol output
  Serial.println(row.postString());

  // UDP Sending
  char buf[2048]; // make buffer for `broadcastTo()`
  row.postString().toCharArray(buf, sizeof(buf)); // string to char array
  // Serial.println(buf);
  udp.broadcastTo(buf ,8089);

  delay(100);
}

method
I create a Line protocol String, make a buffer, convert the string to char [] and send it out.
Question

how do I use AsyncUDPMessage so I can pass the string to it directly?

I am not sure but will char buf[2048] within a loop is a good idea as every time a buffer allocation might make the ESP32 run out of memory? And if AsyncUDPMessage can avoid this concern?

String has .c_str()

the library has AsyncUDPClient example

Yes but there is not mention of AsyncUDPMessage. there is only AsyncUDPPacket

Use udp.print(row.postString().c_str())
AsyncUDPMessage in AsyncUDP library is only a buffer. It is used only in AsyncUDP send function:
size_t AsyncUDPPacket::send(AsyncUDPMessage &message)
{
    return write(message.data(), message.length());
}

So just connect once and then print the information will send the udp to the destination porT?

udp doesn't connect. only the library takes the server and port parameters in a connect like function. the function can only resolve hostname to IP. but the implementation is hidden in not open source espressif SDK

if you don't need nonblocking UDP sending, then you don't need the AsyncUDP library


text:
How to code for cascading multiplexers?
I hope I can get some help on how to get this to work.
I have multiple Sensors (32 of these) which values I want to read. I am using a master multiplexer HC4051 connected to 4 slave multiplexers, this is my wiring:
[here][1]
I tested it using one single multiplexer and it works as intended, but when adding the slave I cannot getting it to work, I am not sure how to code for it.
When using this code:
// 74XX4051 ADDRESS PINS :
#define  M_S0 2
#define  M_S1 3
#define  M_S2 4

#define  S_S0 7
#define  S_S1 6
#define  S_S2 5

// 74XX4051 ANALOG PIN :
#define  Z 0

void setup() {
    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);

    // CONFIGURE SERIAL
    Serial.begin(57600);
}

void loop() {
    int value;

    // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
    for ( byte count = 0; count < 4 ; count++ ) {
         // SET THE ADDRESS
         digitalWrite(M_S0, bitRead(count, 0) );
         digitalWrite(M_S1, bitRead(count, 1) );
         digitalWrite(M_S2, bitRead(count, 2) );

         // LOOP THROUGH ALL THE ADDRESSES OF THE SLAVES
         for ( byte count_1 = 0; count_1 < 32 ; count_1++ ) {
             digitalWrite(S_S0, bitRead(count_1, 0) );
             digitalWrite(S_S1, bitRead(count_1, 1) );
             digitalWrite(S_S2, bitRead(count_1, 2) );

             // READ THE ANALOG VALUE
             value = (bitRead(count_1, 2), bitRead(count_1, 1), bitRead(count_1, 0));
         }

         // READ THE ANALOG FOR THE MASTER ADRESSE
         value = analogRead(Z);

         // SERIAL OUTPUT
         // print : ### value
         Serial.print(bitRead(count, 2));
         Serial.print(bitRead(count, 1));
         Serial.print(bitRead(count, 0));
         Serial.print(' ');
         Serial.println(value);

         delay(100);
     }
}

I am only getting random readings really (the reading LED for the moisture sensor does not switch on when the reading is done).
What I am doing wrong? Any help is appreciated.
UPDATE:
i updated my code as follows :
// Master moisture sensor pins
#define  M_S0 7
#define  M_S1 8
#define  M_S2 9
// Slave moisture sensor pins
#define  S_S0 4
#define  S_S1 5
#define  S_S2 6

// PIN from the transistor to power the sensors only when doing a reading
int sensorVCC = 13;

//  ANALOG PIN :
#define  Z 0

void setup() {
    Serial.begin(9600);
    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);
    pinMode(sensorVCC, OUTPUT);

    digitalWrite(sensorVCC, LOW);
}

void loop() {

    // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
    for (int i = 0; i < 32; i++) {
    digitalWrite(sensorVCC, HIGH);
    delay(100); //make sure the sensor is powere

    digitalWrite(M_S2, i & 0b100000);
    digitalWrite(M_S1, i & 0b010000);
    digitalWrite(M_S0, i & 0b001000);
    digitalWrite(S_S2, i & 0b000100);
    digitalWrite(S_S1, i & 0b000010);
    digitalWrite(S_S0, i & 0b000001);

    delay(1);

    int humidityRaw = analogRead(Z); // 1023 to 0 ===> 0 to 100%
    int humidityReal = map(humidityRaw, 975, 523, 0, 100);
    digitalWrite(sensorVCC, LOW);

    Serial.print("Input ");
    Serial.print(i);
    Serial.print(": ");
    Serial.print(humidityReal);
    Serial.println(" % ");
    delay(1000);
}
}

and this is my output :
    Input 0: 100 %
    Input 1: 0 %
    Input 2: 100 %
    Input 3: 0 %
    .
    .
    .
    Input 0: 0 %
    Input 1: 100 %
    Input 2: 0 %
    Input 3: 0 %
    .
    .
    .
    Input 0: 100 %
    Input 1: 0 %
    Input 2: 0 %
    Input 3: 0 %
    .
    .
    .

ONLY channel 0 is hooked !! .... it seems that it reads with different delays. changing the delay gives me different sequence. what is wrong ?

It becomes much easier if you start thinking in binary.
If you have an 8 bit multiplexer connected to four 8 bit multiplexers that gives you 32 inputs. Four of the inputs on the "master" multiplexer are unused and can be ignored.
You have 32 inputs. That's inputs numbered 0 to 31. In binary that equates to, in full,
0 = 000000   8 = 001000  16 = 010000  24 = 011000
1 = 000001   9 = 001001  17 = 010001  25 = 011001
2 = 000010  10 = 001010  18 = 010010  26 = 011010
3 = 000011  11 = 001011  19 = 010011  27 = 011011
4 = 000100  12 = 001100  20 = 010100  28 = 011100
5 = 000101  13 = 001101  21 = 010101  29 = 011101
6 = 000110  14 = 001110  22 = 010110  30 = 011110
7 = 000111  15 = 001111  23 = 010111  31 = 011111

I have laid it out like that especially so that you see a pattern occurring. Four columns with 8 rows. Four slave multiplexers with 8 inputs. A perfect match. Each column has bits that are distinct to that column. Each row has bits that are unique to that row.  So you could split those bits up and know that the left-hand three bits indicate the column, and the right-hand three bits indicate the row. Between the two it's a unique location in the table.
The same applies to the multiplexers.  The left-hand three bits indicate which slave multiplexer to use, the right-hand three bits which input to use on the selected multiplexer.
So you can loop through each of the 32 inputs with a single loop and examine the individual bits of the input number and apply those bits directly to the select outputs to control the multiplexers - the left-hand bits to the master to select which slave to use, and the right-hand bits to the slaves to select which input to use.
So you have:
for (int i = 0; i < 32; i++) {
    digitalWrite(M_S2, i & 0b100000);
    digitalWrite(M_S1, i & 0b010000);
    digitalWrite(M_S0, i & 0b001000);
    digitalWrite(S_S2, i & 0b000100);
    digitalWrite(S_S1, i & 0b000010);
    digitalWrite(S_S0, i & 0b000001);

    delay(1);

    int reading = analogRead(Z);
    Serial.print("Input ");
    Serial.print(i);
    Serial.print(": ");
    Serial.println(reading);
}

The i & 0b000001 etc performs the same function as bitRead() but is more explicit using a mask that is far more visual as to what it achieves.
I also include a tiny delay after setting the multiplexers up so as to ensure they have settled into their new settings properly before reading. It shouldn't be needed, but it doesn't hurt.

Thanks for the answer .. i updated my code. it kind of works but as i wrote.  i am getting different readings ... ONLY channel 0 is hooked !! .... it seems that it reads with different delays. changing the delay gives me different sequence. what is wrong

I think that you have confused your address encoding in your code. Your complete address space is only a total of 5 bits, decimal 0 to 31. Your two loops (for ( byte count = 0; count < 4 ; count++ ) and for ( byte count_1 = 0; count_1 < 32 ; count_1++ )) are actually counting through a 7 bit address space, just with the 3 MSBs of the inner loop being ignored.
For your 32-input example, I'm going to assume that the master 4051 only has inputs A-D (y0 to y3) connected to downstream muxes and that the analog mux decodes based on the binary value of the input select. Then your digital outputs should correspond to, for byte address as your counter:

S_S0 -> bitRead(address, 0) (LSB)
S_S1 -> bitRead(address, 1)
S_S2 -> bitRead(address, 2)
M_S0 -> bitRead(address, 3)
M_S1 -> bitRead(address, 4)
M_S2 -> constant 0 (MSB)

Thus, your test should only use a for ( byte address = 0; address < 32 ; address++ ) to acquire data from all 32 possible inputs. Remember to have a long enough delay from selecting a different multiplexer input to starting your ADC conversion to avoid errors due to signal settling.
Additionally, you should be calling only one analog read location corresponding to the pin connected to the AnalogInPin in the schematic. You will have to record what the current multiplexer selection to determine which of the 32 inputs is actually being recorded by that conversion. Basically, there's only one 'master" analog input.
Your use of value = (bitRead(count_1, 2),bitRead(count_1, 1),bitRead(count_1, 0)); is confusing and seems incorrect. After you digitalWrite() the new address for your multiplexers, you shouldn't need to read-back the digital pins to know what address you have selected.

Thanks .. i just updated my code. is that what you meant ?


text:
Is it safe to use the same power source for Arduino and its Motor shield?
Is it safe to use a unique 12V 5A DC power source to feed both Arduino and its connected Motor shield, provided that

the motor (connected to the shield) will eat 3A maximum
the Arduino Vin will get the power

Arduino and the shield exchange information, and use both the same power supply, is there some risk of "interference" of some kind?
edit
This is the motor controller shield I intend to use. In the manual, the connections show that

the Arduino and the shield have different power supplies
the Arduino power pins are not used by the shield

Only if the motor gets it's power from the power source itself. If you power it through the shield and Arduino, you will still kill your Arduino.

In my case, when I was running my DC motors at full load, I noticed a large voltage drop in the circuit. This could affect the signals or transmission of data on the Arduino.
It is definitely recommended to power the arduino and motor shield with separate power source. Make sure the the share a common GND.

I'm assuming your shield has its own power input and you feed the circuit from there. If you are sure that your motor shield can hold that much current there shouldn't be any problem. You should see your motor shield's specs for that.
And actually if your shield has the standard arduino layout, it probably has an header goes into Vin pin. So even if you try to supply arduino from USB or power jack along with your power supply, the auto selector circuit of arduino board will use the power from 12 volt power source.

Please see my edit

Yea, it seems it's better to power the arduino seperately then like @goddar tells.


text:
Arduino project feasibility
Question completely rewritten
Trying to assess an Arduino project feasibility. New to Arduino... but did a lot of controller programming (assembly), Roboteq (C) and Phidgets (C++) , using various kinds of motors and sensors ; and reading the Arduino documentation makes me feel confident interfacing and programming shouldn't be an issue.
However, before investing time (and some money) in the project, I thought it'd be better to ask here if Arduino is the right choice, considering

a non-latching Hall sensor is to be connected to Analog 0, analogRead() to return a [0,1023] value, used as a proximity sensor. This should be straight forward.

Question →

while the Arduino runs my program, and is still connected to the PC (USB), is it possible to synchronously or asynchronously send commands from the PC to the Arduino. I.e. can the Arduino poll if there is something coming from USB (synchronous), or is there a way for the PC via USB to have Arduino do something (asynchronously)?

Thank you.

Why a downvote, very new to Arduino are the questions too obvious?

Because your question is too broad. If you are a beginner, start with simpler projects (blinking LED, control the LED via serial, now try it with a motor, read a sensor and print it to serial, try to combine those projects, ...). After you know how to use do simpler stuff, you can use them together to make more complex projects. And learn to structure your program as a state machine and use millis() instead delay() or else doing multiple stuff at the same time won't work or be buggy. With that, you would be able to ask more specific questions.

Completely rewrote the question to simplify the text and go to the point.

Yes, this is possible, but you will need to learn about doing non-blocking serial communication on the Arduino, and perhaps on the PC side as well (though you may just be able to use a terminal program there).  Getting non-blocking serial right is unlikely to be either easier or harder on Arduino than on most other embedded platforms - it is entirely do-able, but tricky, and there are a lot of mistakes that can make for a system that "works sometimes".  The key will be to make few assumptions - don't assume when characters will arrive, or how much time will be between them, etc.

@ChrisStratton Ah.. so there is no convenient USB I/O function.. Did a lot of serial in the past, and wished I could avoid that! Thanks anyway

Your classic Arduino is conceptually a serial device.  On a board such as the Uno the USB port goes through a USB-serial converter (though implemented in a second MCU).  On one such as the Leonardo it actually runs into the application processor, but the default handling still treats it as a serial device.  It is true that USB is different - it both has greater latency, but also if used as USB all the way through gives you some framing possibilities missing in legacy serial.  These tend to be advanced topics however.

It's perfectly doable. As Chris Stratton puts it, it's all about
implementing non-blocking serial communication:

whenever you receive a character, you store it in a buffer
whenever you have a complete command in the buffer, you process it and
reset the buffer

For a line-oriented protocol, it may look something like:
/* Process incoming characters if any. */
while (Serial.available()) {
    static char buffer[BUF_LENGTH];  // incoming command
    static int length = 0;           // command length

    int data = Serial.read();
    if (data == '\r') {              // complete command
        buffer[length] = '\0';       // terminate the string
        if (length)
            exec_command(buffer);    // process
        length = 0;                  // reset buffer
    }
    else if (length < BUF_LENGTH - 1)
        buffer[length++] = data;     // buffer incoming character
}

For a more complete example, you may want to take a look at this simple
Arduino command line interpreter. You connect a terminal
emulator to the Arduino at 9600/8N1, type the "help" command and it
displays:
mode <pin> <mode>: pinMode()
read <pin>: digitalRead()
aread <pin>: analogRead()
write <pin> <value>: digitalWrite()
awrite <pin> <value>: analogWrite()
echo <value>: set echo off (0) or on (1)

You can use it as a template, replace existing commands or add new ones
(the interpreter is just a long if ... else if ...) and – since
it's all non-blocking – add whatever you want to loop().


text:
Using the ATMega328, from an Arduino UNO in a Standalone configuration, and bootloader - I am really lost
I am really despaired. I have spent a full day to understand this, and it seems that I still don't.
I have an Arduino UNO, with an ATMega328, for which I wrote a great piece of code.
Later, I have built a circuit on a bread board, where I want to use that same ATMega328, in a 3.3V configuration, and hence 8MHz oscillator .
So, I understood that I have to write a new boot loader to it (is that correct?)
So I follow many guides available, including the Arduino Standalone, and then I understood that I don't have another chip (ATMega328), in order to use the UNO as a boot loader.
So, I was trying to connect the ATMega328 directly from the bread board to the UNO's serial data, change the boards.txt file to add "ATMega on bread board 8MHz", and tried to boot-loading it, without success. I get the error that it can't connect with the board.
Now I have been told that I can't connect the ATMega328 directly to the UNO serial to boot load it, so my questions are:

Do I really need to go over this hell in order to work with the same
chip that worked with 16MHz, but now on 8MHz at 3.3V? (why
in microchip I could just switch xtal? )
If I do have to boot loading it, and I have one chip, and
an UNO, how can I do that?
How you do that in mass production?

More than a month passed since you posted this question, and there are two answers, below. Did any of them help you? Have you solved your issue?

So do I understand you correctly that you want to lift the ATmega328 IC from the Uno board and use it on a breadboard? That strikes me as an unnecessarily risky proposition just to save a dollar or two for a separate ATmega328p.
Second, you technically might not have to write a new boot loader to the chip, if you don’t intend to reprogram it while it’s on the breadboard, but you definitely need different fuse settings, and the two changes are closely related in the Arduino IDE.
Third, bootloaders on ATmega are incapable of modifying themselves, so if you want to write a new bootloader, you always need a programmer (which can e.g. be your Arduino UNO running the ArduinoISP sketch or ScratchMonkey); I don’t think your single-microcontroller idea would work.
For mass production, you’d just use a programmer. Bootloaders tend not to be used for this, which can lead to situations like this year’s mishap at SparkFun

There is a very nice tutorial by Adafruit, which explains how to get the Arduino Uno run at 3.3v, with minimum hussle and while keeping it's speed at 16Mhz, despite it's a bit out of specs (they claim it shouldn't pose a problem).
The main idea is to replace the voltage regulator and the fuse on the Uno board. This involves some soldering, but will probably give you the fastest results for prototyping.
I would not choose the Arduino Uno for mass production anyway, since there are plenty of Arduino compatible boards that runs at 3.3v (like Arduino Due, Lilypad, and Arduino Pro Mini to name a few. Full list can be found on Wikipedia). As a side note, for mass production, I would probably go with a custom made PCB, and not an off-the-shelf product, considering its high cost.
The link you provided explains how to recreate the Arduino  around the Atmega328p on a breadboard. For that, you will need a USB to serial converter such as the suggested FT232, but please note that this tutorial does not address the issue on stake, which is running the chip at 3.3v (note the specs of the voltage regulator they offer, which is a 5v regulator).


text:
Question on how "f" value is calculated in converting Morse Code to laser audio from this tutorial
I am working on this tutorial,
https://www.hackster.io/SURYATEJA/morse-code-communication-using-laser-module-both-ea1b01
and the author created a "Send" and "Receive" code for encoding and decoding Morse code. He created the "Send" code with the entire alphabet A-Z, but his receive code only has 9 letters.
I thought I could easily add in the missing characters, and even add in numbers, but I am stuck.
His code has 2 values to decode the morse - "a" and "f"
In his receive code he has a value "f" that is supposed to be calculated by the number of spaces, but I cannot see how he comes up with his result.
For example, this is his sending code for "a"
    case 'a':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;

Then this is the receive code;
if(a==4 && f==10) {   Serial.print("a");

I understand the value of 4 for "a", but I cannot understand the value of 10 for "f"
"a" is calculated by assigning a value of 1 for a dot and 3 for a dash and adding the values (in this case one dot and one dash, 1+3 = 4)
He explains how to calculate "f" here in his tutorial, but I still don't understand.

When the LASER falls on the LDR, the value goes beyond 1000, and then it will enter into a loop.
Now quantize the values i.e. if the value goes beyond 1000, then assign it as '1', otherwise assign it as '0'.
Inside a loop, calculate the number of '1's and '0's. Set the counters 'a' and 'f'. Count the number of '1's and store it in 'a' and similarly count the number of '0's and store it in 'f' respectively.
Now check the specific values of 'a' and 'f' respectively. Each character will have different set of 'a' and 'f'. The matching value will be displayed.

That seems to indicate;
Laser on = Over 1000 = 1
Laser off = Under 1000 = 0
So for the letter a, I only see 2 times the laser goes off, not 10.Minof formatting changes

the person that wrote the code did not bother to make the code easily readable by indenting code blocks correctly .... for instance the case 'a':  block that you included in your question .... the case 'a': should  not be indented and the next four lines should be indented ..... all the other case statement blocks should be formatted the same way ...................... the LightsOff(elemPause); should not be called inside the case blocks .... it should be called at the end of MorseDot() and MorseDash() functions ..... that would reduce the length of the program significantly

This is not a good tutorial. The receiver works by assuming 14 dotLen time periods for each character. There is a loop that runs 14 times, with a 200ms delay between each iteration. If the laser is detected, then a is incremented, otherwise f is incremented. This means that the sum of a and f is always 14, and the case where a==0 means nothing was transmitted. The incomplete receiver code shows only 10 options for received characters and leaves out a==5 (which would be R or U), but does define 1 through 10 otherwise.
The receiver code does not differentiate between dots and dashes, it only counts the number of dotLen transitions where light is detected. This is not Morse Code.
The receiver code cannot distinguish between S (dot-dot-dot) and T (dash) because they both have 3 dotLen value. Same for A (dot-dash) vs. N (dash-dot).
If you want to understand decoding morse code, this is not a good tutorial to follow. It does not decode morse code, and I cannot see how it would work even with it's companion transmitter program.

Thanks very much! So assuming I understand it is fake Morse code, and I'm more interested in sending and receiving text data via the laser, would I be able to create a full alpha-numeric set of characters by some method (maybe increasing the amount of dotLen time periods)?

No. I would suggest to abandon this base code for any project. Find something else that already works and learn from that. Do not try to learn from a broken project. It won’t even work on its own.

I agree, Morse code has variable length characters and no carrier detect which makes it challenging to decode.  (Is it "on" or was that noise?  Is it "off" or did I just lose signal?)  I agree with jose, go with a machine-oriented code (such as Baudot or ASCII) and decode that instead.


text:
Choosing a motor for my project
Sorry For my bad English.
I will start to make a mini conveyor (100 cm x 30 cm) with an Arduino Uno.
What is the best motor should I choose for my project ?
- Stepper Motor ?
- DC Motor ?
Etc.
Please help me, I am Newbie.

If you want to control how much the conveyor moves and want to move it a fix distance then stop and move again stepper would be better as you know that each step is equivalent to a certain amount of displacement. Stepper have the disadvantage that is more complicated to control so you will need a special driver.
If you want the conveyor to move continuously at a approximately speed or moving approximately, then DC motor is a good option. It's easier to drive. But if you want the conveyor to go back and forward then you will need a H bridge for the DC motor(similar to the driver for the stepper motor). Also you can get very accurate positioning with a DC motor using a rotary encoder, but it requires a complex software to drive it properly.


text:
Arduino Reaction LED game
I have this code and it is a reaction light game. When you press the button on pin 11 it starts the game and the lights should osculate back and forth. The main goal is to press the button when it hits the middle led and the osculating will slow down. I cannot get the leds to turn on help?
    int ledPin;
    int direction;
    int isChanging;
    unsigned long lastChange;

void setup() {
   //set pins 2 to 10 to be output
  // and LEDs off
   int pin;
    for (pin = 2; pin <= 10; pin++) {
       pinMode(pin, OUTPUT);
       digitalWrite(pin, LOW);
    }
     //set pin 11 to be input
     pinMode(11, INPUT);

     ledPin = 2;
     direction = 1;
     lastChange = millis();
  }

 void loop() {
    if (isChanging) {
    if (millis() - lastChange > 500) {
        //turn off old LED
        digitalWrite(ledPin, LOW);
        //reset time
        lastChange = millis();
        //change the led
        ledPin = ledPin + direction;
        if (ledPin > 10) {
          direction = -1;
        ledPin = 9;
      } else (ledPin < 2); {
        direction = +1;
        ledPin = 3;
     }

       //turn on new LED
        digitalWrite(ledPin, HIGH);
     }
       //check for button
       if (digitalRead(11)) {
        isChanging = 0;
     }
     }
    else {
       //wait for them to let go of the button
       while (digitalRead(11)) {
     }
       //wait for it to be pressed again
       while (!digitalRead(11)) {
     }
       //wait for them to let go of the button
       while (digitalRead(11)) {
     }
    }
   }`

Are you using an external pullup for your button pin?

Your are not explicitly initializing the variable isChanging, so the compiler sets it to 0. This means, that your code will directly go to the last else statement and cannot at any time reach the LED code, because you are not changing the variable in the else statement.
But I don't really understand, why you were using this variable in the first place. Try to use purely non-blocking code. For checking the button you can do something like this:
boolean button_pressed = false;
unsigned long button_timestamp = 0;

void loop(){
  ...
  if(!button_pressed && digitalRead(11)){
    button_pressed = true;
    button_timestamp = millis();
  }
  if(button_pressed && millis() - button_timestamp > 50){
    if(digitalRead(11)){ // real button press
      button_pressed = false;
      // check, if the middle LED is ON and act accordingly
      // or, if the game hasn't started yet, start it
    } else { // just a bounce of the button, not a real button press
      button_pressed = false;
    }
  }

  // LED CODE
  if (millis() - lastChange > 500) {
    ...
  }
}

Note, that this code will not wait for the button to be released, but reacting, when the button was held down for 50ms. You can change this value, to a one, that is more fitting your used button, but it is a good start point.
Also in your LED code, you have to replace the 500 in the millis statement with a variable, since you want to change the speed.
For handling starting the game with the same button, you can use a state variable, which contains a value of means "Game Stopped" or "Game Started".


text:
Connecting 4 servos, 2 motors, hc-05, sr-04 and L293D to Arduino
I am trying to make an obstacle avoiding robot with robotic arm. First, I am from software programming field with no experience in electronics, circuits and Arduino. Using online tutorials so far I am able to blink an led, bluetooth communication between PC and Arduino and sonar range measurement.
After doing a lot of research on internet I have made the following diagram to connect  4 servos, 2 motors, hc-05, sr-04 and L293D to Arduino using "fritzing" software. I have the sketches for running servos and motors but I am not sure the circuit is correct due to the lack of knowledge in electronics. My doubts are,
1) Is 6V supply enough for 4 servos and 2 dc to work?
2) Is the connection between L293D and 2 DC motors correct?
The final robot will look like (I hope!) a "mearm" like robot arm attached on top of an obstacle avoiding robot.

UPDATED:

Can i get the program for this connection?

1) Is 6V supply enough for 4 servos and 2 dc to work?

If the motors are 6V motors then 6V is not only enough, it is what you need. What you should be asking is "Can my power source provide enough current.

2) Is the connection between L293D and 2 DC motors correct?

Not quite. You have only got half your grounds connected up. Also 3,4EN should be connected to Vcc1 not Vcc2.
1A/2A and 3A/4A are the direction/break pins (one high and one low for a direction, both low for break). The EN pins can be (if you wish) used to control the speed with PWM (if you have any spare) - if not then they should be tied to the logic supply voltage, Vcc1, not the power supply voltage, Vcc2, since that can be up to 36V and is way too high for logic inputs like EN.

Thank you for your valuable comments. I have updated the diagram as you said. Can you please check it is correct or not?

Not quite. You seem to have misunderstood the Vcc1/Vcc2 thing. Vcc2 still needs to be connected to your 6V rail, not the 5V one. It was ony 3,4EN that needed to be changed from connecting to Vcc2 to Vcc1.


text:
Split string using a delimiter then saving to different variables
I have a string that looks something like this "43;27;42;27". It is the data from 4 DHT22 temperature sensors, i need to splice this string every ";" and save the number to a variable. In the end, I will have 4 variables, each one for every number. Thanks!
The data comes from another esp wirelessly and I need the data in different strings to a nextion display.
I could also change the delimiters to differ from each other, I am posting this question because I am not sure how i should go about writing all of these 4 values in a string then also "decoding" these strings and assigning each one to a variable.

Have you googled for something like "Arduino parse string"?

Was not sure how I would go about googling this, looking into it right now and I post the answer. Thanks!

splice means connect ... the words you want to search are split and parse


text:
Programming an Arduino Mini 05
So, I recently bought an Arduino Mini (5V, 16MHz), and a USB to Serial Converter.
Provided are the links to both the products:
Arduino Mini,
USB to Serial Converter
Now, I tried programming the mini by connecting the pins in this order:
Rx -> tx, tx-> rx, VCC -> 5V, GND -> GND, DTR -> DTR
The computer detected the USB to Serial converter after I installed the drivers manually. However, the Arduino IDE failed to program the Arduino Mini every single time, even after I swapped the TX, RX pins.
I tried to program the Arduino Mini using an Arduino Uno (I removed the onboard Atmel Atmega microcontroller on the Uno before programming). I connected the pins in this order: TX->TX, RX->RX, 5V-> VCC, GND-> GND, RST -> DTR. From the IDE, I chose Arduino Pro Mini (5V, 16Mhz).
The Mini was programmed successfully this time.
My question: What was wrong with the USB to Serial converter? Why couldn't it program the Arduino Mini with the USB to Serial Converter?

GND -> 5V; I hope that is a typo?

To test the converter, try connecting the TX on the serial converter to the RX of the same converter. Then in the Arduino IDE open the Serial Console. If you send some text, you should receive the same text back.

I did as you said.. It works.. The converter sends the same text back once I send something... But it still can't program the Mini.

I had a problem with a USB to Serial convertor.  It was because the device I had had a dodgy Chinese clone chip and the real manufacturer changed the driver so it wouldn't work properly unless it was a genuine chip.  You can hack the driver inf file to get round it, but I can't remember the details.

The chip on this USB to Serial converter is an Atmel Atmega 8A PU..

Maybe you need to manually reset the board, for programming.

I tried. doesn't work

Are you using windows 7? 32bit or 64bit?

Try to reset manually just after compiling end

I tried.. it doesn't work.... I held the reset button down but the converter still won't program the Mini.... The Mini was programmed using the Arduino Uno successfully btw... It's the converter that is not behaving properly...

It's too late but don't hold the button. Just press once quickly, immediately while compiling going near %100

The Mini was programmed successfully this time

If so, one of them had its tx/rx pins mislabeled.


text:
How come my transistor doesn't work?
I have a TIP 120 to 229 NON 60V 5A transistor
I'm trying to use it to switch an electro magnet. Using the blink example to test it out:
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second
}

pin 13 is connected to the base and I'm trying to powering the magnet with a 12V DC adapter. I'm not sure if the transistor is before or after the magnet, but I'm not sure how that would make a difference.
I'm not great with diagrams but something like this (the power source might be the other way around:

simulate this circuit – Schematic created using CircuitLab
I've tried switching between the collector and the emitter. In one instance the magnet is always active and in one instance it's always passive. What could be wrong?
The cords running of the table in the bottom is just a bit of extra wiring.

A magnet?!?! Do you mean an Electro-Magnet??

How about showing a circuit diagram?

@canadiancyborg Yes

@Majenko sure, gimme a sec!

Also try using a different pin then pin 13, use 12 for example. The led on pin 13 could mess up the transistor.

@Majenko not actually sure I could make a correct one...

Then how about a photo?

@Majenko great idea, updating

@canadiancyborg tried chaning to 12, no difference.

Uhhh transistor wrong way around in the schematic?

@Bradman175 The power is upside down, fixed it.

Is there the only wire from Arduino to the Base of Transistor?
Basically you need something like this:

If you reverse the transistor (E and C), builtin protection diode will be in forward direction, so electro magnet is on.
If you have only one wire to the base, it cannot work as you need current to the base.
If you don't have R1 into the base (about 500R-1K), it'll burn your output eventually. (not if you don't have common ground)
If you have electro magnet between ground and Emitter, you'll have negative current feedback and about 4.2V on L1 tops as there must be some current into the base.

With reverse transistor do you mean reverse collector and emitter? What is "the base"?  I'll put in R1 but would that make this setup not work? I don't have D1 either, what does that do?

If the wire marked by white is +12V, it will be the last case, so no. Also you need common ground, but be carefull, I can see the smoke generator more likely...

The transistor is connected to on the wire with a white mark, is that the right or wrong wire?

White is usually the positive supply. You have to measure it.

You need a resistor between the arduino and the base of the darlington transistor.

The program is fine.
Looking at the first photograph - The Ground of the Arduino needs to be connected to the ground of your circuit.
I do not understand the two-transistor part of your circuit, so I can't say if this is OK or not.  You could also switch the electro-magnet using a relay.

I don't understand the two-transistor part of your circuit - It's a Darlington transistor

@Kingsley, needs to be connected to the ground ok thanks! Is this likely what's causing my problem or is this for some other reason (trying to learn as much as possible).

Can confirm the darlington transistor, concerning the relay, I needed something really fast for my application, so I went with a transistor.

Also How would I do ground arduino in practice? Should i run a wire from ground on the Arduino to the negative pole on the 12V DC-converter?

@Himmators - Yes, the ground of the arduino should be connected to the power supply ground.  Generally all grounds are connected together.

Assuming the - of the power supply is connected to ground your circuit becomes an emitter follower utilizing a Darlington transistor.  In that case the emitter will have the same voltage as the base - the VBE which is about 5 Volts. If you reverse it, you will need about 5 volts VBE to turn it on. Note since it is a transistor there is no protection diode. Best suggestion is to use a MOSFET, that will give you a lot more speed then a power transistor. Substitute the MOSFET in the circuit shown above. Source connects to the Emitter point, the Drain connects to the Collector point and the Gate connects to the base. Use something in the 50 Ohm range for the resistor. Your 12V - becomes ground connected to the Arduino ground. Use a logic level avalanche protected MOSFET and the diode is not needed.

Why don't you add a schematic? Also, I think you overlooked the most important error in the original question, which is that the NPN darlington is used a a high side switch (which is never a good idea for an NPN device). In general, Darlingtons are more robust devices than MOSFETs, especially with inducive loads, so I think it's perfectly acceptable here.

A NPN as a high side and a PNP as a low side are emitter follower circuits, not switches as the transistor cannot be saturated. The emitter follower or common collector circuit provides an ideal buffer amplifier and it is easy to design the circuit however a switch it is not. Check this link: https://www.electronics-notes.com/articles/analogue_circuits/transistor/transistor-common-collector-emitter-follower.php


text:
Having trouble using RTC if I set an ISR for a 1 second timer
I built a sketch using some timer ISR code to get a trigger every second.  (for the Atmega328 chip I use the following code I got form the internets.  It works)
It runs fine and I get a trigger/callback every second.
void setupAtmega328()
{
#ifdef __AVR_ATmega328P__

//      traceDebug("setupAtmega328() entry");
    cli();  // stop interrupts

//    traceDebug("setupAtmega328() 1");
            //set timer1 interrupt at 1Hz
    TCCR1A = 0;// set entire TCCR1A register to 0
    TCCR1B = 0;// same for TCCR1B
    TCNT1 = 0;//initialize counter value to 0
              // set compare match register for 1hz increments
    OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
                  // turn on CTC mode
    TCCR1B |= (1 << WGM12);
    // Set CS12 and CS10 bits for 1024 prescaler
    TCCR1B |= (1 << CS12) | (1 << CS10);
    // enable timer compare interrupt
    TIMSK1 |= (1 << OCIE1A);
//  traceDebug("setupAtmega328() 2");
    sei();//allow interrupts
//  traceDebug("setupAtmega328() 3");

#endif
}

I also wanted to add the capability of a real time clock (RTC) so I got a DS3231.
I downloaded and ran the sample app from this RTCLib on github
The sample code works fine when running under the Arduino IDE
However, when I add the RTC code to my sketch I don't get the results I want/expect.
Specifically, the program seems to hang/halt at the call to:
cli();

I am new to the Arduino platform and not sure what I am missing.
What do I need to do to get the RTC to work in conjunction with an ISR?
I wired the RTC according to the directions from Adafruit's site
I have other arduino boards that use different ISRs, but I have not tried them yet with the rtc since the 328 seems to be the standard arduino boars that is used to do initial work/testing.
How can I use the 3231 RTC AND a 1 second ISR/callback?
EDIT:
I removed the trace/serial output - I had originally added those to track the code to see where I got but i think I exacerbated or added problems in doing that.
for those interested the code is at https://github.com/tjurik/Intervalometer

Provide your whole sketch.

Calling Serial.print after you call cli is ill advised. Serial requires interrupt to send the data (if I remember correctly). Try removing the serial.prints between cli and sei, or at least make the text shorter so the buffer doesn't fill up. PS you can setup the DS3231 to send a pulse every second to the SQW pin. You can connect this pin to one of the Arduino interrupt pins. That way you get a very accurate 1Hz interrupt call.

@gerben - using the rtc to send the 1hz interrupts would be far more desirable!  thanks.  i will try that.

In the Arduino you don't have control how are some essential parts implemented.
For example delay function requires interrupts to be enabled or it'll be deadlocked (for sure).
Serials are little bit better, it'll be working until send buffer gets full. For devices with small RAM it's 16B only! And your traceDebug is little bit longer.
In general ISR should be as short as possible and it's mainly used for setting some flag to be handled in main loop later.
volatile bool flag = false;

ISR(...) {
  flag = true;
}

int main() {
  init();

  while (1) {
    if (flag) {
      do_something();
      flag = false;
    }
  }
}

Yeah, that is how i wrote the code - and then when trying to debug the problem I added serial output which I think made more problems!


text:
Using 2D servo array in my class
I need to use a servo library in my class.
I read this question - Use object of other class within class and it works fine for my LCD application, but now I need to use a 2D servo array in my class. I made one approach, it worked, but I think it is bad programming approach, what is right way to solve my problem?

My main file
#include <SoftwareServo.h>
SoftwareServo servo[5][5];
Servolib Servoarray;

void setup(){
  blah blah blah

My cpp file
#include "Vending.h"
#include "Arduino.h"
#include <SoftwareServo.h>

Servolib::TurnSevo(){
  for(int row=0;row<5;row++){
    for(int collum=0;collum<5;collum++){
      servo[row][collum].attach(Object[row][collum]);
      servo[row][collum].write(0);
    }
  }
}

my .h file
#ifndef Vending_h
#define Vending_h
#include "Arduino.h"
#include <SoftwareServo.h>

class Servolib:SoftwareServo{
public:
  void TurnServo();

private:
  SoftwareServo servo[5][5];
  int Object[5][5]={
    {42,21,20,19,18},
    {37,41,36,38,35},
    {31,33,30,34,39},
    {67,28,66,29,65},
    {56,63,55,64,54}
  };
};
#endif

So this code worked, but please give me better solution.

What do you feel is wrong with that, please?  I could suggest you use a #define or a const int for your array dimensions, rather than having so-called "magic numbers" in the code, but apart from that it looks fine to me. (Also you spelled column wrong, but really this is nit-picking.)

I though i could pass servo object address and work with pointers, similar to this example -> http://arduino.stackexchange.com/questions/9296/use-object-of-other-class-within-class , but i don't know how to pass 2D array using pointers.

You can indeed use pointers, but passing multi-dimensional arrays is a bit of a pain in C(++).
There's a pretty good explanation here.

authors: ريناد الحربي


text:
Servo Driven Through Custom Library Not working Properly
I'm a little new to Arduino, but not to programming or electronics in general.  I'm working on a library that will be more fleshed out later, but I'm having issues getting the basics working properly.
The following code produces the desired behavior if a servo is attached to pin 3:
#include <Servo.h>

Servo myServo;

void setup() {
  myServo.attach(3);
}

void loop() {
  myServo.write(1);
  delay(1000);
  myServo.write(45);
  delay(1000);
  myServo.write(90);
  delay(1000);
  myServo.write(135);
  delay(1000);
  myServo.write(180);
  delay(1000);
}

However, when I try to implement similar functionality in my own library the servo locks and just sort of grinds.  Here's the header file:
#ifndef MotorControl_h
#define MotorControl_h

#include "Arduino.h"
#include "Servo.h"

class MotorControl
{
  public:
    MotorControl(int north, int south, int west, int east);
    void setNorth(int value);
    void setSouth(int value);
    void setWest(int value);
    void setEast(int value);
    int getNorth();
    int getSouth();
    int getWest();
    int getEast();
  private:
    Servo _north;
    Servo _south;
    Servo _west;
    Servo _east;
    int _northVal;
    int _southVal;
    int _westVal;
    int _eastVal;
};

#endif

And here's the .cpp file:
#include "Arduino.h"
#include "MotorControl.h"
#include "Servo.h"

MotorControl::MotorControl(int north, int south, int west, int east)
{
  _north.attach(north);
  _south.attach(south);
  _west.attach(west);
  _east.attach(east);
  _northVal = 0;
  _southVal = 0;
  _westVal = 0;
  _eastVal = 0;
}

void MotorControl::setNorth(int value)
{
  _north.write(value);
  _northVal = value;
}

void MotorControl::setSouth(int value)
{
  _south.write(value);
  _southVal = value;
}

void MotorControl::setWest(int value)
{
  _west.write(value);
  _westVal = value;
}

void MotorControl::setEast(int value)
{
  _east.write(value);
  _eastVal = value;
}

int MotorControl::getNorth()
{
   return _northVal;
}

int MotorControl::getSouth()
{
  return _southVal;
}

int MotorControl::getWest()
{
  return _westVal;
}

int MotorControl::getEast()
{
  return _eastVal;
}

And finally, the code using the above library which should produce the same behavior as the code up top, but does not:
#include <MotorControl.h>

MotorControl mc(3, 5, 6, 9);

void setup() {}

void loop() {
  mc.setNorth(1);
  delay(1000);
  mc.setNorth(45);
  delay(1000);
  mc.setNorth(90);
  delay(1000);
  mc.setNorth(135);
  delay(1000);
  mc.setNorth(180);
  delay(1000);
}

I'm not sure what else to add ... this is running on an Uno R3.
Edit:  This is interesting.  I've tried the code from this example:
How do I initialize a servo object in my own library?
which works out just fine.  I'm still not sure that I see what I'm doing incorrectly here.  I see the differences between my code and the example, but not how they are causing problems.
If it's worth mentioning, I've also stored my library in the libraries folder.  Just throwing out any random detail I can think of.

Hi @MattB, what is your question?

Try expanding you example to have 4 servos and see if that works.  I guess it won't because the Servo library uses timers and the different servos might interfere with each other.  Its just my guess, and I hope I'm wrong.

In you code you could set all the servos to 3, so that its only driving one servo.  The opposite of the above.

Interesting idea @Matt ... I will give that a shot.

@sa_leinad The library I've created is not driving the servo properly.  The servo responds, but does not move to the appropriate positions.

@Matt I just gave it a shot.  No change.  Very confusing...

In C++, when an object is declared as a member of another object, the constructor method of the inner object must be called explicity (see constructors and member initializer lists).
In your code, properties of Servo type can be constructed within the header of the MotorControl constructor:
MotorControl::MotorControl(int north, int south, int west, int east)
    : _north(), _south(), _west(), _east()
{
  _north.attach(north);
  _south.attach(south);
  _west.attach(west);
  _east.attach(east);
  _northVal = 0;
  _southVal = 0;
  _westVal = 0;
  _eastVal = 0;
}

When you create your instance at global scope then you have no control over when exactly the constructor gets called.  If it gets called before init() runs then your attach lines won't work out.  You should have a begin method in your class that handles attaching the servos and call that method from setup.

authors: นนท์ โพธิวาระ


text:
Update variable using buttons
I made a part of code to change the temperature limit for alarm system. On warm days user have to change the temperature limit with buttons and OLED display.
The question is: How can the variable templimit keep its last setup value after many restarts(for many reasons)?
This is the code:
const int  buttonPin = 8;    // up
const int  buttonPin1 = 3;    // down
const int  buttonPin2 = 2;    // enter

int buttonPushCounter;   // counter for the number of button presses
int buttonState;;  // up
int buttonState1;;  // down
int buttonState2;;  // enter
int templimit; // temperature limit for alarm

void setup() {
  Serial.begin(9600);
  Serial.print("Update temperature limit if not wait 10 sec time out");
  updatevalue();
  Serial.print("Done");

}

void loop() {
// do nothing
}

int updatevalue(void) {
  int timenow;
  int timepassed;
  timenow = millis();
  // this loop is just for 10 sec time out
  while (buttonState == LOW and buttonState1 == LOW and buttonState2 == LOW) {
    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down
    timepassed = (millis() - timenow);
    if (timepassed >= 10000)
    return 0;
  }
  while (buttonState2 != HIGH) { // do this until enter is pressed

    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down

    if (buttonState == HIGH) { // up
      buttonPushCounter++;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    if (buttonState1 == HIGH) { // down
      buttonPushCounter-- ;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    delay(700);
  }
  templimit = buttonPushCounter; // update templimit value

}

You can save to EEPROM on pressing the 'Enter' button.

I tried to modify the program. this project I use to limit the value of ADC. can this program be used? because I've tried but it does not work. thank you `#include <EEPROM.h> float read_from_eeprom(unsigned int address) {// read float config; for (byte i = 0; i < sizeof(config); i++) { reinterpret_cast<byte*>(&config)[i] = EEPROM.read(address + i); } return config; } // this constant won't change: const int buttonPin = 8; // up const int buttonPin1 = 7; // down const int buttonPin2 = 6; // enter int tro=A0; int value=0; int out=9; int Switpin=10; int Switch; int buttonPushCounter; // counter f

The microcontroller on the Arduino MEGA boards have 1024 bytes of EEPROM: memory whose values are kept when the board is turned off (like a tiny hard drive).
These values will stay in the EEPROM when the board is turned off and may be retrieved later by another sketch.
I wrote two read/write functions if the value you want to write on EEPROM is negative because temperature has negative values too. Arduino EERROM write word with values between 0-255, also, has a lifetime 100,000 write cycle/ cell.
You can use EEPROM.update(address, value) instead of EEPROM.write(address, value) so the value is written only if differs from the one already saved at the same address.
Save to EEPROM:
void save_to_eeprom(unsigned int address, float config) { // (address, value)

  for (byte i = 0; i < sizeof(config); i++) { // size of config is 4
    EEPROM.write(address + i, reinterpret_cast<byte*>(&config)[i]);
  }

Read from EEPROM:
float read_from_eeprom(unsigned int address) { //(address)
  float config;
  for (byte i = 0; i < sizeof(config); i++) { // size of config is 4
    reinterpret_cast<byte*>(&config)[i] = EEPROM.read(address + i);
  }
  return config;
}

This is how templimit will keep its last value after restart, the full code is:
#include <EEPROM.h>

  float read_from_eeprom(unsigned int address) {// read
    float config;
    for (byte i = 0; i < sizeof(config); i++) {
      reinterpret_cast<byte*>(&config)[i] = EEPROM.read(address + i);
    }
    return config;
  }

// this constant won't change:
const int  buttonPin = 8;    // up
const int  buttonPin1 = 3;    // down
const int  buttonPin2 = 2;    // enter

// Variables will change:
int buttonPushCounter;   // counter for the number of button presses
int buttonState;;  // up
int buttonState1;;  // down
int buttonState2;;  // enter
int templimit = read_from_eeprom(20); // temperature limit for alarm

void setup() {
  Serial.begin(9600);
  Serial.println("Update temperature limit if not wait 10 sec for time out");
  updatevalue();
  Serial.println("Done");
  Serial.println(templimit); // temperature limit for alarm

}

void loop() {
  // do nothing
}

int updatevalue(void) {
  int timenow;
  int timepassed;
  int counter = 10;

  timenow = millis();
  while (buttonState == LOW and buttonState1 == LOW and buttonState2 == LOW) { // this loop is just for 10 sec time out
    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down
    timepassed = (millis() - timenow);
    delay(1000);
    Serial.println(counter--);
    if (timepassed >= 10000)
      return 0;
  }
  while (buttonState2 != HIGH) { // do this until enter is pressed

    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down

    if (buttonState == HIGH) { // up
      buttonPushCounter++;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    if (buttonState1 == HIGH) { // down
      buttonPushCounter-- ;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    delay(700);
  }

  save_to_eeprom(20, buttonPushCounter); // save to address 20 tha value it can be negative

}

void save_to_eeprom(unsigned int address, float config) {// write value it can be negative

  for (byte i = 0; i < sizeof(config); i++) {
    EEPROM.write(address + i, reinterpret_cast<byte*>(&config)[i]);
  }
}

An Arduino Uno has 512 bytes of non-volitile memory called EEPROM or Electrically Erasable Programmable Read Only Memory. Other Arduino platforms might have more. Accessing it is complex.  Fortunately there is an Arduino EEPROM library already written for you.  Your value is stored in a type int so I would use the read() and update() methods in the EEPROM library.  The read is self explanatory.  But the update, unlike the write, only runs if what is in the EEPROM location is different from what you want to write.  In this way we save the EEPROM a little bit of ware and tare.  As EEPROMs usually have a finite number of write cycles until they start failing.  Which usually is in the tens of thousands.

Atmega328p has 1024 bytes of EEPROM.