text:
Serial.read() keeps returning the same value over and over
This code keeps on returning 'S' with the Serial.read().
#include <Servo.h>
#define trig 10
#define echo 9
int pinMotorRN=3;
int pinMotorRP=4;
int pinMotorLN=5;
int pinMotorLP=6;
long distance;
long duration;
Servo myservo;
void setup() {
  pinMode(pinMotorRP, OUTPUT);
  pinMode(pinMotorRN, OUTPUT);
  pinMode(pinMotorLP, OUTPUT);
  pinMode(pinMotorLN, OUTPUT);
  Serial.begin(9600);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  myservo.attach(8);
}
void loop() {
  Lid();
  while(Serial.available() == 0);
  char val = Serial.read() ;//reads the signal
  delay(1);
  Serial.println(val);
  if(val == 'F'){
    Forward();
  }
  else if(val == 'B'){
    Backward();
  }
  else if(val == 'R'){
    Left();
  }
  else if(val == 'L'){
     Right();
  }
  else
    Stop();
}
void Stop()
{
  digitalWrite(pinMotorRP, HIGH);
  digitalWrite(pinMotorRN, HIGH);
  digitalWrite(pinMotorLP, HIGH);
  digitalWrite(pinMotorLN, HIGH);
}
void Backward()
{
  digitalWrite(pinMotorRP, HIGH);
  digitalWrite(pinMotorRN, LOW);
  digitalWrite(pinMotorLP, HIGH);
  digitalWrite(pinMotorLN, LOW);
}
void Right()
{
  digitalWrite(pinMotorRP, HIGH);
  digitalWrite(pinMotorRN, LOW);
  digitalWrite(pinMotorLP, LOW);
  digitalWrite(pinMotorLN, HIGH);
}
void Left()
{
  digitalWrite(pinMotorRP, LOW);
  digitalWrite(pinMotorRN, HIGH);
  digitalWrite(pinMotorLP, HIGH);
  digitalWrite(pinMotorLN, LOW);
}
void Forward()
{
  digitalWrite(pinMotorRP, LOW);
  digitalWrite(pinMotorRN, HIGH);
  digitalWrite(pinMotorLP, LOW);
  digitalWrite(pinMotorLN, HIGH);
}
void Lid(){
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
  distance = duration*0.034/2;
  distance = 11;
  if(distance <= 10){
    myservo.write(180);
    delay(2000);
  }
  else
    myservo.write(0);
}

Note that the app im using is Arduino RC bluetooth car controller

Does it print 'S' over and over or keep executing the stop sequence? Because your terminal is probably sending "<some_letter>", so you'd see stop (the default) get executed 1 or 2 times per keystroke (depending on whether the terminal ends a line with , ,  or both), plus one more if you actually typed an 'S'. In any case, this code shouldn't be delivering a long stream of anything when you aren't typing.

If you are trying to read a character on the serial port shouldn’t “while(Serial.available() == 0);” be “while(Serial.available() > 0);

@MrFixIt87: The semicolon following the while-expression is an empty statement. So the whole loop translates to: "While there are zero characters in the serial buffer, do nothing".


text:
Compiling Error 3 Wire LCD
When this 3 wire LCD code is compiled the following message results:
NewLiquidCrystal-master\I2CIO.cpp:35:26: fatal error: ../Wire/Wire.h: No such file or directory
#include <../Wire/Wire.h>                         ^
compilation terminated.
exit status 1
Error compiling for board Arduino Nano.
Thanks for your help.

 // Original LiquidCrystal library that can be inherited from to support other
 // connectivity:
 // https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home

 #include <LiquidCrystal_SR_LCD3.h>

 // Standard HD44780 20x4 LCD display driven via 3 output pins to a 4094 8-bit
 // shift register like 74HC4094 pebblev2's MC14094

  // This demo was written for the PebbleV2 to test LiquidCrystal_SR_LCD3, but it
 // should work with other LiquidCrystal Displays that are 20x4.
 // http://www.freetronics.com/pages/pebble-v2
 // https://github.com/lukeweston/pebble20

 // Data are the input bits
 // Clock tells the SR that the data pin holds the next valid bit
 // Strobe gets data input to be made visible on the parallel output pins.

 const int PIN_LCD_STROBE         =  2;  // Out: LCD IC4094 shift-register strobe
 const int PIN_LCD_DATA           =  3;  // Out: LCD IC4094 shift-register data
 const int PIN_LCD_CLOCK          =  4;  // Out: LCD IC4094 shift-register clock
 const int PIN_LCD_BACKLIGHT      =  5;  // Out: LCD backlight (PWM)

 // srdata / srclock / strobe
 LiquidCrystal_SR_LCD3 lcd(PIN_LCD_DATA, PIN_LCD_CLOCK, PIN_LCD_STROBE);

 // Creat a set of new characters
 byte heart[8] = {
   0b00000, 0b01010, 0b11111, 0b11111, 0b11111, 0b01110, 0b00100, 0b00000
 };

 byte smiley[8] = {
   0b00000, 0b00000, 0b01010, 0b00000, 0b00000, 0b10001, 0b01110, 0b00000
 };

 byte frownie[8] = {
   0b00000, 0b00000, 0b01010, 0b00000, 0b00000, 0b00000, 0b01110, 0b10001
 };

byte armsDown[8] = {
   0b00100, 0b01010, 0b00100, 0b00100, 0b01110, 0b10101, 0b00100, 0b01010
 };

 byte armsUp[8] = {
   0b00100, 0b01010, 0b00100, 0b10101, 0b01110, 0b00100, 0b00100, 0b01010
 };

 void setup(){
     pinMode(PIN_LCD_BACKLIGHT, OUTPUT);
     analogWrite(PIN_LCD_BACKLIGHT, 80);

     lcd.begin(20, 4);               // initialize the lcd

     // load characters to the LCD
     lcd.createChar(0, smiley);
     lcd.createChar(1, frownie);
     lcd.createChar(2, armsDown);
     lcd.createChar(3, armsUp);
     lcd.createChar(4, heart);

     lcd.home ();                   // go home
     lcd.setCursor (0, 0);
     lcd.print(F("LiquidCrystal_SRLCD3"));
     lcd.setCursor (0, 1);
     lcd.print(F("he.."));
     lcd.setCursor (0, 2);
     lcd.print(F("..lo"));
     lcd.setCursor (0, 3);
     lcd.print(F("World "));
     lcd.print(char(4));
     lcd.print(char(2));
     lcd.print(char(3));
     delay(2000);
 }

void loop()
 {
     for (int i = 5; i <= 15; i++){
       lcd.setCursor ( i, 1 );
       lcd.print(char(random(0,2)));
       delay(100);
       lcd.setCursor ( i, 1 );
       lcd.print(F(" "));
     }

     for (int i = 15; i >= 5; i--){
       lcd.setCursor ( i, 1 );
       lcd.print(char(random(0,2)));
       delay(100);
       lcd.setCursor ( i, 1 );
  lcd.print(F(" "));
     }

     // Turn the display on/off
     lcd.setCursor ( 5, 2 );
     lcd.print(F("Turn screen off"));
     delay(1000);
     lcd.noDisplay();
     delay(1000);
     lcd.display();

     lcd.setCursor ( 5, 2 );
     lcd.print(F("Toggle Cursor  "));
     delay(1000);
     lcd.setCursor ( 19, 2 );
     lcd.cursor();
     delay(2000);
     lcd.noCursor();

     lcd.setCursor ( 5, 2 );
     lcd.print(F("Toggle Blink   "));
     lcd.setCursor ( 19, 2 );
     lcd.blink();
     delay(2000);
     lcd.noBlink();

     lcd.setCursor ( 5, 2 );
     lcd.print(F("Scroll screen  "));
     delay(1000);
 // This is an autoscroll demo, not super useful but here just in case.
 //    lcd.setCursor(16,0);
 //     lcd.autoscroll();
 //     // print from 0 to 9:
 //     for (uint8_t thisChar = 0; thisChar < 10; thisChar++) {
 //   lcd.print(char(2));
 //  delay(250);
 //  lcd.print(char(3));
 //  delay(250);
 //     }
 //     // turn off automatic scro
 //     lcd.noAutoscroll();

     for (uint8_t positionCounter = 0; positionCounter < 10; positionCounter++) {
       // scroll one position left:
       lcd.scrollDisplayLeft();
       // wait a bit:
       delay(50);
     }

     // scroll 29 positions (string length + display length) to the right
     // to move it offscreen right:
     for (uint8_t positionCounter = 0; positionCounter < 20; positionCounter++) {
       // scroll one position right:
       lcd.scrollDisplayRight();
       // wait a bit:
       delay(50);
    }

       // scroll 16 positions (display length + string length) to the left
       // to move it back to center:
     for (uint8_t positionCounter = 0; positionCounter < 10; positionCounter++) {
       // scroll one position left:
       lcd.scrollDisplayLeft();
       // wait a bit:
       delay(50);
     }
     lcd.setCursor ( 5, 2 );
     lcd.print(F("               "));
 }

The error message is rather clear, the file Wire.h is not in the expected location. Either edit the file I2CIO.cpp and change the #include statement or create that directory and copy the file to it.

Thanks for your reply. I'm still learning Arduino programming and uncertain how to create the directory. I want to verify that after the directory is created I2CI).cpp is copied in the newly created directory? What should be the name of the directory? Thanks for your assistance.

Go to the directory where I2CIO.cpp is located. Change one directory up with cd ... Create the new directory with mkdir Wire. Copy Wire.h to the new directory.

The programmer did not include the Wire/Wire.h. I don't see in the code any reference to this library.  Is it wire.h or wire/wire.h?

It's there in the LiquidCrystal_V1.2.1.zip. In newer versions it's gone.

In the 3wire sketch there is no reference to #include  wire/wire or wire.h. Still not sure of the exact lib file needed. Is it wire.h or wire/wire.h? Why does compile error result when there is no reference to the wire lib? Thanks Tom

source: Stack Exchange

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

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

sort: votes


text:
millis() replace delay() question
// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED12=0;
unsigned long previousMillisLED13=0;

unsigned long previousMillisLED3=0;

// different intervals for each LED
int intervalLED12 = 500;
int intervalLED13 = 5000;

int intervalLED3 = 2000;

// each LED gets a state varaible
boolean LED13state = false;     // the LED will turn ON in the first iteration of loop()
boolean LED12state = false;     // need to seed the light to be OFF

void setup() {
   pinMode(13, OUTPUT);
   pinMode(12, OUTPUT);

   pinMode(3, OUTPUT);

}
void loop() {
   // get current time stamp
   // only need one for both if-statements
   unsigned long currentMillis = millis();

   // time to toggle LED on Pin 12?
   if ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
      LED12state = !LED12state;
      digitalWrite(12, LED12state);
      // save current time to pin 12's previousMillis
      previousMillisLED12 = currentMillis;
   }

// time to toggle LED on Pin 13?
  if ((unsigned long)(currentMillis - previousMillisLED13) >= intervalLED13) {
      LED13state = !LED13state;
      digitalWrite(13, LED13state);
      // save current time to pin 13's previousMillis
      previousMillisLED13 = currentMillis;
  }
}

My questions:

Didn't see the led12 and led13 have 10 times defferency, almost same intervals, why?
How can I use millis() as simple as delay?
Is that a must to use if?

The leds blink with different intervals. Have you connected the leds and resistors in the right way? The function millis can be used as a delay, but not in the same way. When a sketch with delay needs to be transformed to millis, then often a large part of the sketch has to be rewritten.

Note that currentMillis - previousMillisLED12 is an unsigned long. Explicitly casting it to unsigned long is redundant.

What do you mean by 3.?

@Jot Thank you, I just delete the delay(1000) and put 'if    ' section instead of.

@Edgar Bonet I'll change it.

@chrisl, I mean is this the only way to do like: " ' if' ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
LED12state = !LED12state; "

Yes, that is the only way. See also the blink-without-delay: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

Your Timing is working, you can test it with the Serial monitor. So your problem is at some other place. Using delay() is from my perspective not a good solution, you did it better the way you already made.
For testing your sketch I included the communication for the Serial Montior (I had to comment out the LED activation since this is working in a different way on my board, and I also made the intervalls Shorter to see better the effect within the test sketch). Here you find the necessary changes and the output of the Serial Monitor.
My recommendation is to look with a simple Sketch if you are able to switch on/off your LEDs sperately without Timing to come closer to your problem. I dont think it is the Timing/use of millis().
#include <M5Stack.h> // needed for my board

// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED12 = 0;
unsigned long previousMillisLED13 = 0;

unsigned long previousMillisLED3 = 0;

// different intervals for each LED
int intervalLED12 = 50;
int intervalLED13 = 500;

int intervalLED3 = 2000;

// each LED gets a state varaible
boolean LED13state = false;     // the LED will turn ON in the first iteration of loop()
boolean LED12state = false;     // need to seed the light to be OFF

void setup() {
  Serial.begin(9600);
  //  pinMode(13, OUTPUT);
  //  pinMode(12, OUTPUT);
  //  pinMode(3, OUTPUT);
}
void loop() {
  // get current time stamp
  // only need one for both if-statements
  unsigned long currentMillis = millis();

  // time to toggle LED on Pin 12?
  if ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
    LED12state = !LED12state;
    // digitalWrite(12, LED12state);
    // save current time to pin 12's previousMillis
    previousMillisLED12 = currentMillis;
  }

  // time to toggle LED on Pin 13?
  if ((unsigned long)(currentMillis - previousMillisLED13) >= intervalLED13) {
    LED13state = !LED13state;
    // digitalWrite(13, LED13state);
    // save current time to pin 13's previousMillis
    previousMillisLED13 = currentMillis;
  }
  Serial.print("LED12: ");
  Serial.print(LED12state);
  Serial.print("  LED13: ");
  Serial.println(LED13state);

}

Thank you RJPlog, I'll test it.

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


text:
changing state of an LED using a pushbutton leads to unstable result
I am trying to run this code:
const int buttonPin = 7;
const int ledPin13 =  13;

int buttonState = 0;
int lastButtonState = buttonState;
bool flag = true;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin13, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {

  buttonState = digitalRead(buttonPin);

  if (buttonState = HIGH && lastButtonState != buttonState) {
    flag = !flag;
    if (flag){
      digitalWrite(ledPin13, LOW);
    } else {
      digitalWrite(ledPin13, HIGH);
    }
  }
}

on this SimulIDE model:

<circuit reactStep="50" animate="0" type="simulide_0.1" noLinStep="10" noLinAcc="5" speed="1000000">

Node-16:
<item labelrot="0" y="-204" valLabRot="0" valLabelx="0" valLabely="0" hflip="1" vflip="1" x="-220" labelx="-16" labely="-24" Show_id="false" objectName="Node-16" itemtype="Node" id="Node-16" rotation="0"/>

Arduino Uno-4:
<item hflip="1" Show_id="true" valLabely="0" itemtype="Arduino" vflip="1" labelx="0" objectName="Arduino Uno-4" labely="-20" y="-244" Ser_Port="false" labelrot="0" rotation="0" Program="../../Google Drive/Active projects/SRL/Students/Damian2019/Simulation/20190409/noDelay_20190409/noDelay_20190409.ino.standard.hex" Ser_Monitor="false" id="Arduino Uno-4" valLabelx="0" Mhz="16" valLabRot="0" x="-148"/>

Resistor-3:
<item Unit=" O" hflip="1" Show_id="false" valLabely="6" itemtype="Resistor" Show_res="true" vflip="1" labelx="-12" objectName="Resistor-3" labely="-24" y="-164" labelrot="0" rotation="-90" Resistance="100" id="Resistor-3" valLabelx="-16" valLabRot="0" x="-220"/>

Push-2:
<item labelrot="0" y="-308" valLabRot="0" valLabelx="0" valLabely="0" hflip="1" vflip="1" x="-100" labelx="-16" labely="-24" Show_id="false" objectName="Push-2" itemtype="Push" id="Push-2" rotation="0"/>

Connector-5:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Resistor-3-lPin" labelx="-16" objectName="Connector-5" labely="-24" y="-148" endpinid="Arduino Uno-4-GND0" enodeid="Circ_eNode-6" labelrot="0" pointList="-220,-148,-220,-108,-140,-108" rotation="0" id="Connector-5" valLabelx="0" valLabRot="0" x="-220"/>

Connector-11:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Push-2-rnod" labelx="-16" objectName="Connector-11" labely="-24" y="-308" endpinid="Arduino Uno-4-V5V" enodeid="Circ_eNode-12" labelrot="0" pointList="-84,-308,44,-308,44,-148,4,-148" rotation="0" id="Connector-11" valLabelx="0" valLabRot="0" x="-84"/>

Connector-9:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Push-2-lnod" labelx="-16" objectName="Connector-9" labely="-24" y="-308" endpinid="Node-16-0" enodeid="enode-15" labelrot="0" pointList="-116,-308,-220,-308,-220,-204" rotation="0" id="Connector-9" valLabelx="0" valLabRot="0" x="-116"/>

Connector-15:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Arduino Uno-4-PD7" labelx="-16" objectName="Connector-15" labely="-24" y="-172" endpinid="Node-16-1" enodeid="enode-15" labelrot="0" pointList="-140,-172,-172,-172,-172,-204,-220,-204" rotation="0" id="Connector-15" valLabelx="0" valLabRot="0" x="-140"/>

Connector-17:
<item hflip="1" Show_id="false" valLabely="0" itemtype="Connector" vflip="1" startpinid="Node-16-2" labelx="-16" objectName="Connector-17" labely="-24" y="-204" endpinid="Resistor-3-rPin" enodeid="enode-15" labelrot="0" pointList="-220,-204,-220,-180" rotation="0" id="Connector-17" valLabelx="0" valLabRot="0" x="-220"/>

PlotterWidget-13:
<item modal="false" childrenRect="" normalGeometry="" baseSize="" geometry="" sizeIncrement="" windowOpacity="1" windowModified="false" enabled="true" maximumSize="" childrenRegion="" maximumHeight="200" inputMethodHints="0" mouseTracking="false" minimumSize="" frameGeometry="" sizeHint="" windowIconText="" locale="" minimumSizeHint="" height="200" isActiveWindow="true" x="0" accessibleName="" layoutDirection="0" autoFillBackground="false" width="200" windowFilePath="" windowModality="0" maximized="false" sizePolicy="" MinVolt="-500" fullScreen="false" windowTitle="" windowIcon="" maximumWidth="1000" objectName="PlotterWidget-13" toolTip="" toolTipDuration="-1" focus="false" MaxVolt="500" palette="" font="MS Shell Dlg 2,8.25,-1,5,50,0,0,0,0,0" whatsThis="" pos="" minimumWidth="200" minimumHeight="200" size="" focusPolicy="0" itemtype="Plotter" updatesEnabled="true" accessibleDescription="" y="0" rect="" frameSize="" minimized="false" acceptDrops="false" styleSheet="" cursor="" visible="false" statusTip="" contextMenuPolicy="1"/>

SerialPortWidget-14:
<item modal="false" childrenRect="" normalGeometry="" SettingsProp="COM1,0,3,0,0,0" baseSize="" geometry="" sizeIncrement="" windowOpacity="1" windowModified="false" enabled="true" maximumSize="" childrenRegion="" maximumHeight="170" inputMethodHints="0" mouseTracking="false" minimumSize="" frameGeometry="" sizeHint="" windowIconText="" locale="" minimumSizeHint="" height="141" isActiveWindow="true" x="0" accessibleName="" layoutDirection="0" autoFillBackground="false" width="313" windowFilePath="" windowModality="0" maximized="false" sizePolicy="" fullScreen="false" windowTitle="Settings" windowIcon="" maximumWidth="450" objectName="SerialPortWidget-14" toolTip="" toolTipDuration="-1" focus="false" palette="" font="MS Shell Dlg 2,8.25,-1,5,50,0,0,0,0,0" whatsThis="" pos="" minimumWidth="0" minimumHeight="0" size="" focusPolicy="0" itemtype="SerialPort" updatesEnabled="true" accessibleDescription="" y="0" rect="" frameSize="" minimized="false" acceptDrops="false" styleSheet="" cursor="" visible="false" statusTip="" contextMenuPolicy="1"/>

</circuit>

and I expect the LED to be turned on-off everytime I push the button, however the result is unstable:

I would appreciate if you could help me know if there is something wrong with my code or circuit and I should expect the same behavior on an actual hardware, or this is a simulation issue?
P.S.1. All file can also be downloaded from here.
P.S.2. I'm using this example from Arduino.org website.
P.S.3. I also tried using an actual Arduino, also implementing the suggestions below. However the issue is not resolved. You may see the video here.

You need the state-change-detection: https://www.arduino.cc/en/Tutorial/StateChangeDetection

I identify a few problems here:

The 100 Ohm pulldown resistor for the button is way too low. 1 kOhm to 100 kOhm is typically used here.
if( buttonState = HIGH ) does not compare, it assigns buttonState to HIGH (overwriting the value read with digitalRead(buttonPin)). Use the compare-for-equality operator == here, otherwise the if just checks if buttonState has been assigned a "truthlike" value (incidentally, HIGH is one of them).
As others have already commented, lastButtonState must be set somewhere after the if-block!

Since many Arduinos do have pullup resistors built in, I'd say: drop the resistor completely, instead initialize the button input pin (7) to use its built-in pullup resistor ... this will invert the logic and you'll have to connect the button between pin 7 and GND (i.e. swapping button and resistor), though:
    pinMode(buttonPin, INPUT_PULLUP);

This will have the same result as if you replaced the 100 Ohm resistor with a 20 kOhm resistor after swapping button and resistor -- but that resistor is now inside the Arduino. (Take care if you use "Arduino-compatible" boards; sometimes they lack the pullup resistors or have them fixed!).
There still is one problem: bouncing. Pressing a mechanical button leads to the contacts inside the button to bounce a bit against each other, leading to a very fast HIGH-LOW-HIGH-LOW-etc signal before it settles on the target state. You can alleviate this a bit by adding a delay(5) at the end of your loop(), but using a button library (e.g. Button, available in the Arduino IDE Library Manager) that debounces the signal will lead to better results most of the time.
This will lead to this code (also including the ternary operator hint by Michel Keijzers):
const int buttonPin = 7;
const int ledPin13 =  13;

int buttonState = 0;
int lastButtonState = buttonState;
bool flag = true;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin13, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  buttonState = digitalRead(buttonPin);

  if (buttonState == LOW && lastButtonState != buttonState) {
    flag = !flag;
    digitalWrite(ledPin13, flag ? LOW : HIGH);
  }

  lastButtonState = buttonState;
  delay(5);
}

This should do the trick (I didn't try it, though).

OMG how could I make such a mistake!!! Thanks for pointing it out. one issue you should consider is that Arduino uno doesn't have INPUT_PULLDOWN. Apparently only Zero has this? I get the error INPUT_PULLDOWN was not declared in this scope

ok. it seems the pinMode(buttonPin, INPUT_PULLDOWN); is equivalent of pinMode(pin, INPUT); digitalWrite(pin, LOW); and pinMode(buttonPin, INPUT_PULLUP); is pinMode(pin, INPUT); digitalWrite(pin, HIGH); and that syntax doesn't work properly on some versions of Arduino IDE.

@Foad You're right, according to https://www.arduino.cc/en/Tutorial/DigitalPins INPUT_PULLDOWN seems to be rather seldom... but INPUT_PULLUP should work. Using this would invert the logic on the button pin, though. I'll edit to reflect that.

could you be kind to 1. draw the circuit using the pullup resistor 2. point me a good button library? thanks again.

@Foad I added a link to the most simple button library with debouncing from the Arduino IDE Library Manager; documentation is on its github page. Drawing the circuit must have to wait until I'm back home.

Certain Changes in your code:
const int buttonPin = 7;
const int ledPin13 =  13;

int buttonState = 0;
int lastButtonState = buttonState;
bool flag = true;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin13, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {

  buttonState = digitalRead(buttonPin);

  if (buttonState == HIGH && lastButtonState != buttonState) {
    lastButtonState = buttonState;
    flag =!flag;
    if (flag){
      digitalWrite(ledPin13, LOW);
    } else {
      digitalWrite(ledPin13, HIGH);
    }
  }
}

Secondly your hardware model is not good.
ANODE of LED must be connected to PIN13 and Cathode to GND. And switch must be placed between 3.3 V and Pin7 only.
In your model by closing switch you are shorting 3.3V and GND. If you had provided an external pullup then you should use at minimum a 4.7K resistor value. 100ohm never works.
I don't have software for Design so I used Paint and made a sketch for you.

simulate this circuit – Schematic created using CircuitLab

ah my bad the lastButtonState = buttonState; was in the actual code but I dropped it accidentally in the example. would you be kind to draw the correct circuit? I'm not sure if I understand exactly what you mean.

The OP is using 5V, not 3.3v. And how is his circuit's switch shorting 3.3V/5V to ground? If pin7 were an output, and LOW, it would be a low resistance path to ground. It might be a good idea to put a 1K resistor on Pin7.

In your diagram, you need a current-limiting resistor on the LED or it will both draw too much current from pin13 and over-drive the LED (But I think the OP is using the built-in LED on pin 13 rather than adding an external LED.)

There's still a problem in the code: lastButtonState will always be HIGH, because it is inside the if(buttonState == HIGH) block.

There are already great answers, but I also found out about the interrupt functionality:
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING);
}

void loop() {
  digitalWrite(ledPin, state);
}

void blink() {
  state = !state;
}

some point:

no matter using interrupt or the methods above tho process will not achieve stable / deterministic result. The issue lies in the hardware of the push-button and there will be fluctuations which can be interpreted by the MCU. One way to alleviate is to use delay.
The
attachInterrupt has four modes LOW, Change, FALLING and RISING. The FALLING and RISING modes are the one to be used. the other two also lead to very unpredictable result.
Only pins 1 and 2 can be used for interrupts.
There is also the option to mix the two methods which you can see here, but I'm not sure if it will improve the stability.

I used this video and information on this page.

This is a comment (but could not use text alignment in a comment):
Instead of
if (flag){
  digitalWrite(ledPin13, LOW);
} else {
  digitalWrite(ledPin13, HIGH);
}

You can use:
digitalWrite(ledPin13, flag ? LOW : HIGH);

(It is functionally 100% equal though).

nice. I did not know we have ternary operator also here On Arduino language.

Actually the Arduino IDE is very similar to C++. The ternary operator is from the C language.

Very nice that Arduino language is compliant with the common C/C++ compilers.

Also several libraries are written in C++ (so you can use OO/classes); however some features are better to skip (like the Boost library if it works at all), because of dynamic memory management versus having only a few KB SRAM available.

I do not understand why they down voted you. I appreciate your support anyway.

Probably because it should be a comment (but code alignment is only possible inside an answer).

@Foad You could think of the Arduino sketch file as a part of a standard C/C++ file. Prior to compiling, the sketch is just inserted into the main file of a standard GCC build tree, included library files and hardware libraries are just copied next to it. Then gcc takes over; you could see its output if you enable verbose compiling in the Arduino IDE preferences.

@jsotola basically int 0, 1, bool false, true and LOW, HIGH are the same?

@orithena is it avr-gcc behind the scene?

@Foad Which gcc exactly is used depends on the board selected (for my boards, it's gcc-xtensa, but I only use ESP8266 boards ^^). Verbose compile output will show the exact compiler binary that is used.

@orithena how/where do I set the verbos option?

@jsotola it could be dangerous to assume values for LOW and HIGH, what if ST decides LOW is 25 and HIGH is 38? Not likely, but I wouldn't want my code to be depending on the values of LOW and HIGH.

@Foad See the screenshot at https://www.arduino.cc/en/Main/Preferences, "Show verbose output during [x] compilation".


text:
Interrupt is activated as soon as I insert a jumper wire into the port
I have written a very simple code to test the interrupt functionality of my Arduino Uno expansion board:
const byte buttonPin3 = 3;

void setup() {
  pinMode(buttonPin3, INPUT);
  attachInterrupt(digitalPinToInterrupt(buttonPin3), trigger, CHANGE);

  Serial.begin(9600);
}

void loop() {
}

void trigger(){
  Serial.println("trigger");
}

However, the Serial.println("trigger"); is activated as soon as I insert a jumper wire into pins 2 or 3. It seems like I have broken the microcontroller. I would appreciate if you could help me know if there is something wrong with my code or I need to change the microcontroller? if I have to replace the MCU can I just use any identical AVR and just place it on the DIP IC socket adaptor?
P.S. Filip Franik asked me to draw the schematics:

simulate this circuit – Schematic created using CircuitLab
P.S. I used the official Button's tutorial and now everything works just fine. I can't reproduce the issue anymore for no obvious reason!.

In the circuit that you posted there is not button or jumper wire to somewhere else. In the current state, both pins will only show 0 as their state. Please explain what jumper cable you actually mean, where you are connecting it and where it goes from there.

Connect both Pin2 and Pin3 with two 1K resistors to ground.
When a pin that's set as INPUT is "floating" (it's not connected to anything) the value on it is "undetermined" and interrupt can trigger when a neighboring pin status changes, or even just magically by itself. The 1K resistors (called pulldown resistors) will make sure that pin is set to LOW when it's not connected using the jumper.
This circuit should put a stable 0V on Pin3 when switch is unpressed and 5V when it's pressed. You should be able to verify that using any voltage meter.

If the issue persists then swapping the microcontroller on the Arduino is just one of the steps you need to perform. You would also need to burn a bootloader on the chip. It's not a hard procedure but it requires a second Arduino.

Doing this there are no continuous interrupts. However, as soon as I remove the wire to connect it to another place where it should be it starts triggering again!

Can you draw your connections? I have problems picturing your design. Also use a voltage meter and check if there is a 5V after you put the jumper and resistor on the pin.

added to the post

"...as soon as I remove the wire to connect it to another place where it should be it starts triggering again!" That makes sense. When the pin is not connected to anything, it begins floating again.

CMOS inputs "float" when not connected to anything, and will give semi-random values. You can either connect the pin to ground via a medium value resistor (1kΩ-10kΩ), or set the pin to INPUT_PULLUP mode.
You shouldn't move the interrupt pin connections around while the Arduino is running. As soon as you disconnect the wire from the input, it begins floating again, and can detect semi-random HIGH/LOW values.
If you use an external pull-down resistor, put a connector after the ground connection and move that connection, so the pull-down resistor is always connected to the pin.
If you use INPUT_PULLUP mode, you should not use a pull down or pull up resistor. This mode connects the pin weakly to +5V, which will hold it at a HIGH value when not connected to anything. You would then ground it to trigger an interrupt. In INPUT_PULLUP mode you can probably disconnect the wire from the interrupt pin without triggering interrupts.


text:
Alternative for IRF520 mosfet in Arduino shutdown schema
I’am using IRF520 mosfet according to this schema to shut down Arduino by low level on output to 10K ohms resistor
Schema of my device is

The issue is that IRF520 took too much place
Is it possible to substitute IRF520 with smaller mosfet?
Additional info:
I measured average power consumption – it’s about 22 mA on 12V = 0.264W
IRF520 is for 70W max according to datasheets.
The base schema is

check out irlz44n much better option.

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

I going try 2N7000 - http://www.futurlec.com/Transistors/2N7000.shtml, since 200mA should be enought for my schema. What do you think about resistors? Should I change them or I can left 10K and 120K?

That transistor has a very high R_DSON. You should be looking for sub-ohm resistances.

@Majenko I'm not very good with mosfets, should I increase resistance of R1 or R2 for 2N7000?

No. Choose a different mosfet with a lower resistance.

No need to increase r1 r2. If anything they are already too big. 2n7000 or 2n7002 if you want even smaller devices is more than adequate for your application. Its rds is 6ohm max and if you look at the id vs. Vds chart it is even smaller for a Typical 2n7000. So people arguing for its high rds are reading the spec without understanding it.

I'll try 2N7000 and 2N7002, thanks. What do you think how much I should decrease R1 and R2 to make them work in my schema instead of IRF520?

R1 is there to prevent ringing / overloading the mcu and R2 to help bleed off the charge on the gate. they are useful only for high speed switching on big mosfet. the typical value for R1 is in the <10R range (with a driver). and R2 <1K. If you are switching at high speed (100Khz or over and pushpull), I would consider putting a 47 - 110R as R1 and go without R2.

After picking of the resistors I found that 2N7000 working well for my case with R1 = 10K and R2 = 5.6K. Also 2N7002 is a compact version of 2N7000 for surface mount. I will update my question by this information, thanks

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


text:
Powering Multiple Servos From One Battery- What is my circuit missing?
I'm working on a robotics project right now and my limited DIYer knowledge of electrical circuits is failing me. I need to power 7 Rage Standard Metal Gear Servos (RGRS104-16-6vm) and 4 RadioShack Micro Servos using a Tenergy 6V 3300mAh NiMH Battery Pack. I've made a diagram of the circuit I'd like to make, but I feel like there's more to this type of circuit than I've planned for. There are only 9 servo connections because two pairs of Rage Servos will be wired together to share the same battery and signal connection. I'm also open to using a different battery if that's what it takes to make the robot run smoothly (It has to use a rechargeable battery though; It's meant to be portable.) Also, the Arduino has it's own battery, so no worries there.
Would you please point out what I need to add to my circuit to make sure it works properly?
Thanks in advance!

More Info:
Rage Standard Metal Gear Servo RGRS104-16-6vm
Dimensions: 40.8 × 20.1 × 38 mm
Weight: 56 g
Operating Speed: 0.18sec/60degree (4.8V), 0.16sec/60degree (6V)
Stall Torque: 9kg.cm/125.2oz.in(4.8V), 10.2kg.cm/141.9oz.in(6V)
Operating Voltage: 4.8V~6V
Control System: Analog
Direction: CCW
Operating Angle: 180degree
Required Pulse: 500us-2500us
Bearing Type: 2BB
Gear Type: Metal
Motor Type: Carbon
Connector Wire Length: 30 cm.
RadioShack Micro Servo
Voltage: 4.8~6.0V
Torque: 1.5kg/cm at 4.8V; 1.8kg/cm at 6.0V
Speed: 0.12/60ТА at 4.8V; 0.10/60ТА at 6.0V
Size: 23x11.5x24mm
Weight: 8.6 g
Use Angle: <=160ТА
Tenergy 6V 3300mAh NiMH Battery Pack
Chemistry: Ni-MH
Cell Size: Sub-C
Nominal Voltage (V): 6
Capacity (mAh): 3300
Max Continuous Discharge Current: 6A
Battery Charging Current:
Standard: 1A
Weight: 10oz.
Dimensions: 112 x 46 x 23mm (LxWxT)
Connector: Hitech
Link to Diagram: https://i.sstatic.net/L4GtP.jpg

Servo's can draw spike currents, so you theoretically need a big capacitor to be able to supply such power needs. It may also help to use a battery type that has a higher maximal discharge current (but I believe internal resistance of a battery may rise over time).

Also, paint is a nice program to draw, but for drawing circuit boards you should try Fritzing, cadsoft eagle or something like easyeda. Fritzing has a board view that resembles your drawing, but with pre-made components.

I'm voting to close this question as off-topic because it is entirely about RC servos and not at all in any way about Arduino.  Try an RC hobby site for the best advice, in particular, in figuring out if your pack is four or five cell, and in the case of the latter if it is or is not appropriate to use directly.

One thing to ask, it is not clear if you are going to run the Arduino Uno off the same battery, or off a different battery?
If the same battery, then you are likely going to need to create an V+ output for the Uno, but will need to ensure that any drain from multiple servo's running are not going to impact on the voltage supplied to the arduino, and also that the voltage supplied is compatiable with the Uno (e.g. don't run 6V+ into the 3V outlet)
Just to note as well, the Arduino Uno has (to my knowledge) only has about 6 PWM pins which is what you will need to drive the servo's through the signal pin. You can add I2C PWM expanders which give you more pins (e.g. https://www.adafruit.com/product/815) but YMMV

the Arduino Uno has (to my knowledge) only has about 6 PWM pins which is what you will need to drive the servo's through the signal pin. - Actually that's not true (and it took me by surprise too when I found out): The Arduino uses timer interrupts not PWM in the servo library. It's set to drive 12 servos per timer, and the '328P has 1 timer allocated to it, so can directly drive 12 servos on any pins of your choice no problem.

No, the Arduino is powered by a separate battery.


text:
Wake Arduino (Atmega328) from sleep with ADXL345 interrupt
So I'm relatively new to microcontrollers, and I'm having a problem implementing a feature I want for a project.
I've learned about putting an Atmega328P to sleep from this tutorial. I'm using an Arduino Nano, so I only get my current down to ~9mA rather than the µAs the tutor is getting. Nonetheless, it demonstrates the abstraction I want to learn for when I move to just the Atmega328 with no board.
I've learned to wake up my microcontroller from sleep with a falling external interrupt on INT0/D2 from a simple button. My ISR is empty and just boots me back to the loop, which is fine. As an aside, I have heard that it is better to have simple and short ISR's, but I am not completely sure why.
My question is, can I use my ADXL345 to trigger an interrupt that wakes my Arduino? I am semi-familiar with using an ADXL345 over I2C, although I don't understand why my Sparkfun ADXL345 requires different wiring than my unbranded one, but that's for a separate question I suppose.
So my question is, is it possible, and if so, how? Also, is the I2C connection meaningful for an ADXL345 that is primarily being used as a wake-up interrupt on the Z-axis only? (My use case is an item someone picks up, which wakes my embedded circuit out of sleep and begins logging load cell and UWB sensor data, and is put back to sleep after a period of inactivity).
Thanks in advance - I appreciate any and all help!

If you don't have anything in the ISR, you could use EMPTY_INTERRUPT(INT0_vect); instead. Secondly, the Atmega328P can wake up from falling edge interrupt to (though the datasheets states differently). What I sometimes to is disabled the INT0 interrupt inside the ISR, so it only fires once; then enable it again before I go to sleep. The accelerometer probably doesn't remember any settings, so you'd still need the I2C to setup the ADXL345 at power-up.

So I would have a setup function, a loop function, and an ISR. I would configure the ADXL345 in my setup, run a loop that puts my microcontroller to sleep, and use an ISR for when my accelerometer receives a double tap (for example). In the ISR, the microcontroller wakes from sleep, and I would also disable the interrupt, and point the program back to my setup to refresh my accelerometer setup, reattach an interrupt, and run the loop to go to sleep again. Does this sound correct?

Mostly, yes. You only need to setup the accelerometer once. By "power-up" I meant applying power. So e.g. when you insert new batteries.

Do you have any example code where you do this all?

When using an ADXL345 to trigger an interrupt to wake an Arduino, I2C (or SPI) need not be relevant.  Instead, you can just connect pin 8 or 9 (INT1, INT2) of the ADXL345 directly to the Arduino pin that wakes the Arduino.  Note, INT1 and INT2 in this answer refer to pins 8 and 9 of the ADXL345.
On the ADXL345, map the wake-up event (or events) to whichever of INT1 or INT2 (pin 8 or 9 on the ADXL345) you've connected to the Arduino.  By sending commands from the Arduino to the ADXL345, you can map multiple events to INT1 and INT2 on the ADXL345, and might have both of them connected to different pins on the Arduino for different purposes.
As noted on page 20 of the Analog Devices ADXL345.pdf Rev. E datasheet,

The default configuration of the interrupt pins is active high. This can be changed to active low by setting the INT_INVERT bit in the
  DATA_FORMAT (Address 0x31) register.
How do I toggle bits in an ADXL345?

You can use SPI or I2C to set up registers on the ADXL345.  You will need to configure the unit before it does anything, because it powers up into standby mode.  See the second paragraph of POWER SEQUENCING, page 13 in spec sheet, and see Table 6 on that same page:

At power-up, the device is in standby mode, awaiting a command to enter measurement mode, and all sensor functions are off. After the device is instructed to enter measurement mode, all sensor functions are available.

When you say map the wake-up event to INT1 (digital 2) on the Arduino, do you mean in Arduino code? Also, how do I toggle bits in an ADXL345 - do I do it through my Arduino IDE?

@A.Orchard, please see added paragraphs at end of answer.  Also, I rephrased some 'map' refs, eg, “By sending commands from the Arduino to the ADXL345, you can map multiple events to INT1 and INT2 on the ADXL345”


text:
running a dc motor with a small L298N module and an arduino and the L298N library
I have a small L298N module which I would like to use to run a couple of dc motors. The module I have is smaller than most of the ones you see on eBay, it looks like this...

I am trying to use the following library :
https://github.com/AndreaLombardo/L298N
I have managed to get the motor going forwards and backwards, but the problem is, this module doesn't have a pin for enable ( EN for PWM from the Arduino) and the library seems to require this; therefore I can't control the speed of the motors.
Does anyone have any experience with these modules? Is there a different technique I should be using? Is there another library that works with these kind of modules?
All help appreciated.

PWM is used to control the duty cycle and not the voltage directly so your PWM will work directly on the input pins of motor driver and you will be able to control the speed.
just use analogWrite on the input pin which was held HIGH and HOLD the other pin to LOW. If you desire to change the direction while simultaneously controlling the speed. just analogWrite both the pins. Just keep in mind that the duty cycle of both the pins should not be tweaked simultaneously. while the speed is being controlled in one direction the other pin should be at analogWrite(other,0).

Thanks very much for the answer. Do you know of any libraries that will handle the pin writing such that I can just send an int for speed / direction? ( similar to the other library I referenced ). Or do you have some example code of how to set the speed manually?

you can use this snippet in your code if you want
void Loop()
{
   //this is basically to demostrate how you can control the speed
   // and direction simultaneously
   for(i=0;i<256;i+=51)
   {
      analogWrite(motorForwardPin,i);
      analogWrite(motorBackwardPin,0);
      delay(2000);
   }
   for(i=0;i<256;i+=51)
   {
      analogWrite(motorForwardPin,0);
      analogWrite(motorBackwardPin,i);
      delay(2000);
   }
}

and it's better if you don't use a library for this purpose.


text:
Using all ten capacitive touch inputs on the ESP32
I am using a Wemos Pro ESP32 development board and would like to be able to use all ten of the available capacitive touch inputs. I am able to get readings from nine of them but not T1. Here is the pin diagram for the board I have.

Running this code on my board produces no difference in reading for T1...
#define numTouchPins 10
byte touchPins[] = { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9 };
byte touch[10] = {};

void setup() {
    Serial.begin(115200);
    delay(1000);
}

void loop() {
    for( byte pin = 0; pin < numTouchPins; ++ pin ) {
        touch[pin] = touchRead( touchPins[pin] );
    }
    for( byte i = 0; i < 10; ++i ) {
        Serial.print( touch[i] );
        Serial.print( "\t" );
    }
    Serial.println();
}

So the reason for this is that T1 is on GPIO0 which is also connected to a button labeled 0 on the board. Now I realise this is needed in order to select between the ROM serial bootloader mode and the normal execution mode... But, is there a way to change the pinmode from digital-in to touch-in once normal boot has completed? Is there something I can write in the Arduino setup() method that would make this pin behave like the other touch pins?

is there a way to change the pinmode from digital-in to touch-in once normal boot has completed?

You already are. However it will make no difference since that pin is connected to external hardware - namely the button and a pullup resistor.
You cannot have touch inputs connected to anything else.  The only way to get the touch to work on that input is to physically remove the pullup resistor and even maybe the button. Touch inputs are "touchy" about what else is connected since even a button that's not connected to anything else can effect the capacitance on the pin.

Ok. So you can't use Touch1 on GPIO0 because of this hardware setup ... but can you set it to be usable on another pin? In this hackaday article they talk about an internal multiplexer allowing you to map one pin's functionality to another's  ... Any idea how that would be done?

No clue whatsoever. Probably not possible with analog pins - that kind of functionality is usually only for moving things like UART, SPI, etc.


text:
How to make I2C work on RS485?
I'm trying to optimize the communication (minimize wires) on a project where I can control a motor and toggle some 230V devices by using RS485 and I2C.
On this project, I'm using an Arduino (Mega) for the control panel (buttons, potmeters, LED segment display (I2C) etc.).
I'm using the RS485 protocol (Modbus RTU) to control an inverter by using a MAX485 TTL converter. Now I also have a relay board (8 channel) to be able to toggle some lightning and sound devices. Both the inverter and the relay board, as well as the power supply, are located in another box, which I call the power box. Between the control panel and the power box will be a cable.
[Control Panel (with arduino mega)] <--cable--> [power box (with inverter, 8 channel relay board and 230V devices)]
I've got the following requirements:

The cable should have a minimum amount of wires (5V, Ground, 485+(A) and 485-(B) for sure)
The total length of the cable varies from 1 to 3 meters.
The signal should be reliable.

Now the relay board uses 8 channels. I've bought an I2C expander (PCF8574) to minimize that to 2 wires (SDA, SCL).
I'm thinking of using the existing 485 lines to control the inverter AND the relay board. So no additional wires are required. But theoretically I can't get it to work. So before I try to invent it.

Can I do I2C communication over the RS485 as well somehow by putting another converter?
If you recommand to just go with 6 wires (power, RS485 and I2C), how reliable is my I2C line going to be on 3 meters? What pull-up values do you recommand? (24AWG wire in mind, but also using a close-by LED segment display, so 2 I2C devices on different distances). I've read posts saying:

The rule of thumb is maximum 50 cm for a normal 100 kHz to 400 kHz I2C bus.

Or can I use some other protocol/trick? Either minimalize wires, or boost signal by a I2C buffer? (recommendations?)

I2C needs two signals referenced to ground and RS485 needs a twisted pair.  This is very different.  By the time you convert the signal you might have found it would have been easier to just throw away your I2C peripherals and buy new RS485 peripherals.  I2C, SPI and other similar protocols were meant to reduce the pins on peripheral chips normally located on the same PCB.  They are not meant to go long distances.  You may find you need to drop the speed on the I2C bus.  And to debug problems you likely will have to use an oscilloscope.

add a small arduino as a RS485 to I2C converter or connect the relays to it

An oscilloscope is too expensive for me. How badly is it to not use a twisted pair for rs485 on a length of 3 meters?

And what if i did use twisted pair, can the 5v and gnd line be used on a twisted pair? Or will that create a voltage drop?

Twisted pair is designed to work over longer distances. Because it is a twisted pair, any noise picked up by one wire is canceled out at the far end by the complimentary noise picked up by the other wire. That is why it is used. The reason it is not always used: Because twisted pair requires extra hardware to transmit it and extra hardware to receive it.  Adding to the cost of the product. You can not simply connect a 5v digital signal and ground to a twisted pair. To take advantage of the noise immunity you need to drive the twisted pair with equal but opposite voltages. Like USB or Ethernet.

To answer your previous comment, RS485 is supposed to use twisted pair.  If you do not, then the individual wires of the pair may not pick up the same but opposite amounts of noise.  So there may be noise at the termination (far end).  Twisted pair is easy to get and is everywhere thanks to the phone company and Ethernet cable.  Both types of cables are normally twisted pair.  And you can always use your own wire and twisted them together your self.

The oscilloscope was to check on how bad the I2C signal looked after several meters of cable.  To try different terminating resistors.  To see what might be interfering w/the signal (light dimmers, motors, fans, relays...).  Not to check on the RS485 signal.

I have to use the same cable for my power and for the rs485. So i guess twisted pair it is. The power can't be transformed to -5v. So what are the disadvabtages of 5v and 0v on a twsited pair then? And i can't twist wires myself as it should be 1 cable containing the wires. I know what you meant with the oscilloscope.

I2C and RS485 are such vastly different protocols with such vastly different signalling needs that they cannot share the same cables.
Further, I2C is not designed for connecting with long cables - it's meant for use between chips on a PCB.
The simplest "Arduino" solution would be to create a new RS485 device on your RS485 bus using another MAX485 and a small Arduino (micro, nano, etc) that responds to MODBUS RTU instructions and controls the relay board for you.

I was afraid so. But when i think about 'simple maintainence' i actually want to avoid another micro controller with software. The best solution would be just a swap of standard components. Anything you can think of?

I know of nothing. Ask Google for a MODBUS RTU compatible relay controller. Be prepared to pay lots.

Mhm, true. Industrial.. Always expensive. What about keep using i2c with a buffer/booster? I also read some posts saying they can have up to 20 meters with a slow rate and the correct resistors and such?

You're starting to enter the hacky and unreliable (and probably not working at all) area. If you're going to hack something together at least do it within the framework of your existing protocol. Just use an Arduino at the remote end like I suggested. That's by far the best low-cost option. Anything hacked together to try and force two protocols down one set of wires will be far worse in the long run, if it's even possible.

I meant when using 6 wires (own pair for i2c) but doing it on a longer distance. But yes, probably right, better use another microcontroller on the 485 bus then. I can lose the i2c completely.


text:
How to run Arduino code on Linux?
I want to use an MFRC522 module as explained in this video.
But is it possible to get around with Arduino and use a TTL to USB converter to connect RC522 directly to my PC running Ubuntu?
Using the RC222's UART interface, should I rewrite Arduino libraries from scratch for PC or is there a way to easily port the libraries?

are you wanting to keep it in c++?

no. the language is not important at all. Is it feasible in you opinion? @ChadG

Arduino libraries rely on the Arduino API to operate (usually). Things like the Serial object are expected to be defined.
Linux doesn't have any of that stuff, so you would have to implement it all yourself.
There is the "Wiring Pi" project for (obviously) the Raspberry Pi that implements the majority of the Arudino API, but whether that could be made to run on Linux on a PC is anyone's guess.
It may be simpler to just examine the existing library (and datasheet) and implement it yourself in your chosen language.


text:
What's wrong with this code?
//Error message Arduino: 1.8.5 (Windows 10), Placa:"Arduino/Genuino Uno"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

(.text+0x0): multiple definition of `__vector_7'

libraries\IRremote\IRremote.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Erro ao compilar para a placa Arduino/Genuino Uno.

Este relatório teria mais informação com a
opção «Mostrar mensagens detalhadas durante a
compilação» seleccionada nas Preferências.
//

Code
#include <IRremote.h>      //must copy IRremote library to arduino libraries
#include <Servo.h>
#define plus 0xFD10EF   //clockwise rotation button
#define minus 0xFD50AF  //counter clockwise rotation button

int RECV_PIN = 2;       //IR receiver pin
Servo servo;
int val;                //rotation angle
bool cwRotation, ccwRotation;  //the states of rotation

IRrecv irrecv(RECV_PIN);

decode_results results;

const int pinoledlar=10;
int portaled4 = 12;
int portaled3 = 8;
int portaled2 = 11;
#define pinopir 3
int acionamento;
const int sirene=7;
int portaLDR = A5; //Porta analógica utilizada pelo LDR

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  servo.attach(9);     //servo pin
  pinMode(pinoledlar,OUTPUT);
  pinMode(portaled2, OUTPUT);
  pinMode(portaled3, OUTPUT);
  pinMode(portaled4, OUTPUT);
  pinMode(pinopir,INPUT);
  pinMode(sirene,OUTPUT);
}

void loop()
{
    acionamento=digitalRead(pinopir);
    if (irrecv.decode(&results))
    {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value

    if (results.value == plus)
    {
      cwRotation = !cwRotation;      //toggle the rotation value
      ccwRotation = false;         //no rotation in this direction
    }

    if (results.value == minus)
    {
      ccwRotation = !ccwRotation;   //toggle the rotation value
      cwRotation = false;            //no rotation in this direction
    }
    }
    if (cwRotation && (val != 175))
    {
    val++;                         //for colockwise button
    }
    if (ccwRotation && (val != 0))
    {
    val--;                         //for counter colockwise button
    }
    servo.write(val);
    delay(20);          //General speed

    if (acionamento==HIGH)//se detetar movimento
    {
    digitalWrite(pinoledlar,LOW);
    tone(sirene,440,1000);
    delay(1500);
    }
    else// senão detetar movimento
    {
    digitalWrite(pinoledlar,HIGH);
    noTone(sirene);
    delay(1500);

    int estado = analogRead(portaLDR);  //Lê o valor fornecido pelo LDR

    // Caso o valor lido na porta analógica seja maior do que
    // 800, acende o LED
    // Ajuste o valor abaixo de acordo com o seu circuito
    if (estado > 900)
    {
    digitalWrite(portaled2, HIGH);
    digitalWrite(portaled3, HIGH);
    digitalWrite(portaled4, HIGH);
    }
    else  //Caso contrário, apaga o led
    {
    digitalWrite(portaled2, LOW);
    digitalWrite(portaled3, LOW);
    digitalWrite(portaled4, LOW);
    }
}
}

IRemote and Servo both want to define the compare interrupt of the same timer. Find a way to shift one library to another hardware timer. (TIMER2_COMPA_vect according to https://arduino.stackexchange.com/a/12389/30175)

You have a very common problem that is documented all over. You have two libraries, Servo and IRremote, that are both trying to use the same hardware timer. Do a little Google searching for possible fixes. You will need to either find a different Servo library or a different IRremote library.

Ty for the fast response i will try something before getting into any foward details.

I have solved my problem. I changed the IRremote timer and it works just fine.


text:
Convert UNIX Timestamp
I have an UNIX Timestamp in my Arduino Sketch and would like to get the day of the week of this timestamp (1-7).
How can I convert the timestamp to get the day of the week?

Do you mean, your program will be given a UNIX Timestamp number as data and should produce a day-of-the-week number?  Or that you have a timestamp number and want to know its day-of-the-week number?  If the latter, the Unix date command can tell you, via format code +%u.  Eg, if date +%s says 1455407637 (for Sat Feb 13 16:53:57 MST 2016), date -d@1455407637 +%u says 6.

The simplest solution to that problem is to download the Time library and use the weekday() function:
int weekday(time_t t); // the weekday for the given time

Cheers!

One caveat, the breakTime() code at line 168 of Time.cpp computes Wday = (t/(60*60*24) + 4) % 7) + 1, ie, it apparently ignores leap seconds [26 in number since 1972] so for 26 seconds before every midnight the day-of-the-week calc will be off by 1.

Ignore previous comment.  As noted in wikipedia's Unix time article, Unix timestamps don't count leap seconds, so they are locally correct and calculations near midnight will be ok, except during a leap second itself.  Also see Eric Raymond's Time, Clock, and Calendar Programming In C article, and the article Unix leap seconds.

UNIX timestamps are also kept in GMT/UTC time.  So you may run into problems with it being some hours out.  If so look to the functions gmtime() Vs locatime().  You may need to set your time-zone.  Oh and watch out for daylight savings time if it matters for your project.


text:
Hall effect sensor direction detection using arduino
I'm using a hall effect sensor A1356 (linear application) to measure the amount of fluid in a container. The fluid is in constant use. My doubt is I'm placing the sensor and the magnet assembly in place, such that when it is exactly half filled, the magnet's center will align with the center of the sensor. In this condition I get 100% duty cycle output from the sensor.
Condition 1: If the fluid is filled then the magnet moves above the sensor and the duty cycle reduces say to 90%.
Condition 2: If the fluid is consumed then the magnet will move below the sensor and the duty cycle reduces to say 90%.
How do I differentiate between the rise and fall of the fluid? Or is there a better way of orienting the magnet and the sensor such that this problem could be avoided?
I'm interfacing it with an Arduino UNO

Two sensors? If the lower one activates then the level is low (and if it deactivates it is lower still). If the higher one activates then the level is high (and if it deactivates it is higher still). If both activate then the level is about right.

its is a one way of doing it but i am supposed to use only one sensor to reduce the cost

Do you have a bipolar or unipolar device? If it's bipolar, and you position both the sensor and magnet correctly, you can see if it's above or below.

According to the data sheet (see below) the no-field PWM output is mid-range; north poles reduce it & south increase.
So if you had an arrangement whereby the float had north down & south up, ie a vertical bar-magnet, this would presumably give a rise-before-0 or fall-before-0 at the float vanishes, or a fall-to-minimum an rise-to-maximum as the float centres? The bit in the middle could be interesting!
From the datasheet:
"The presence of a south polarity magnetic field,
perpendicular to the branded surface of the package face,
increases the output duty cycle from its quiescent value toward
the maximum duty cycle limit. The amount of the output duty
cycle increase is proportional to the magnitude of the magnetic
field applied. Conversely, the application of a north polarity
field decreases the output duty cycle from its quiescent value."


text:
Arduino Uno + Adafruit Ultimate GPS Shield Serial issue
I've had an Arduino Uno for a couple of months-making basic sketches-and recently purchased an Adafruit ultimate GPS shield and attached with soldered headers. This shield has 2 options for reading data, direct and soft serial.
I can sit near a window in my house and receive data using the direct method. This is just due to uploading a blank sketch and reading the serial window. Next, I tried to use one of the examples included in the Adafruit_GPS library and the serial window shows a bunch of nonsense updating.
Has anyone else seen this problem? I'm wondering if its the digital pins on the Arduino that I may have damaged since the example code has a simple phrase to display at the start, and I don't even get this.
Code eg: Serial.println("Get version!").
Just to verify, both boards have power and the direct method was giving me good GPS readings, the serial method gave me junk (not even a simple printed phrase to start), and I verified the Soft Serial switch was flipped and the baud rates matched in code and serial window.
I've attached pictures of the direct method results from that in the serial window, and then the junk results using an unaltered sample serial code. Any help with this would be appreciated.

It looks like you are using the wrong baud rate somewhere.
You mentioned that you had checked your baud rates but check again because the second terminal window looked as if the baud rate was wrong.
In your terminal window. Go to bottom right hand corner where it says 9600 and change it to match the serial speed set in your arduino code.
Or it could be that you are receiving too much data as per the bottom of this article:  https://learn.adafruit.com/adafruit-ultimate-gps-logger-shield/soft-serial-connect

Definitely a baud rate problem. The GPS is sending at 9600.
When you use a sketch to receive the data, the SoftwareSerial .begin should be set to 9600. The Serial.begin should be set to a rate higher than 9600, so that the Arduino cannot fall behind in relaying the data to the PC.
If this does not solve you problem, please post your sketch and a wiring diagram so we can analyze it further.


text:
Programming many Arduinos simultaneously with a wireless broadcast
I will have many microcontroller-based devices which will be independent from each other, but all will run the same program.
I would like to upload a program to all of them at the same time with a wireless broadcast. Ideally the user would plug in a USB controller to his computer, and upload a program from the Arduino environment as if s/he were programming a single device.
To get a better idea of what I'm talking about, please take a look at this video. This was achieved with Atmel microcontrollers but a custom-made, non-Arduino bootloader.
From a Google search for "Arduino infrared programming" this interesting project came up. The main drawback is that the reset button still has to be pressed manually. Ideally I would like the devices to be in a low-power state by default, and wake up to receive a program when they sense a signal from the controller. Still, this may be a good starting point for me.
I just wanted to get some perspectives from people who are familiar with Arduinos as to whether they think this is feasible before I jump in.

Check this website http://lowpowerlab.com/blog/category/moteino/wireless-programming/

Which platform are you using to upload your sketches from?

TL;DR -
You have the options of either BlueTooth or XBee (amongst others: IR, for example?) for wireless uploading. However, I believe that only one board can be uploaded to, at a time, so you will need to cycle through the boards one at a time, see Programming multiple ATMegas/Arduinos at once.

When uploading a sketch or using a programmer (for sketch or bootloader), the software does not just write the code, it actually communicates with the microcontroller.
You can't program them all at once. But you can program them one by one in some automatic way.

Your question is a very interesting one, and asks a question that I am sure that I would never have thought of, but would be extremely useful and labour saving, especially if one has, as I do, many Arduino controlled sensor points located around the house. Here is one rather inelegant solution that may be worth trying.
Wireless upload hardware
If you use BlueTooth to wirelessly upload your sketches, then this solution might be of use, Wireless upload program to Arduino without USB cable. Note that this solution ties up pins D0 and D1:

But be careful that it maybe not compatible with some projects which need to use the D0 and D1 as hardware UART TX, RX. Because the wireless programmer needs to permanently occupy the two pins.

Looking at it, it employs a custom Arduino Wireless Programmer, to which you may have been referring in your question. However, don't be fooled by the name, it is simply a Bluetooth shield. It is basically a BT HC-05 (or similar) device, bolted onto an Arduino, see also Bluetooth Wireless Upload.
Alternatively, en lieu of BlueTooth, you could use XBee devices, see Wireless Programming of Arduino. The advantage of using XBees is that you would not have to go through the pairing new device loop (see below), that would be required when using BT. Instead you would merely have to cycle through the XBee network IDs.
However, in addition to that, you would need to automate the switching of BT devices, selecting the appropriate port and uploading to each Arduino in turn, as you are not able to broadcast sketches. (If am I wrong, then will someone please correct me).
Selecting the port and uploading the sketch
You could use a script along with the command line version of the Arduino IDE, to select the port that the BT device is connected to, before each upload. How you do this will vary for which ever platform you are compiling upon, see Command line Arduino compiling and downloading? This can be done using the environment variable ARDUINO_COMPORT (see the possibly out of date Windows command line build), or the arduino cmd line option --port <portname> ( see the man page). The sketch would then be uploaded using the option --upload <filename>. You could do this in one fell swoop:
arduino --upload --port <portname> FILE.ino

Note that on Windows you should use arduino_debug.exe.
Or you could use Ino, if you are not using a Windows PC... but that might make the next part, which deals with the looping more complex than it needs be.
Selecting each of the Arduinos (i.e. the BT devices)
Next, you would need to add a loop to the script, that pairs the PC to each BT device in turn and thereafter calls the Arduino IDE, for the port selection and uploading. Unfortunately, this would not be platform agnostic at all, and would require a different solution for what ever platform you are using. Take a look at Bluetooth from the Command Line, but for Windows you would probably require the Blue Tooth Command Line tools suite.
On OS X you may be best off resorting to using AppleScript, see Connect to bluetooth device (iPhone) via command line on MacOSX, as the cmd line tools for controlling BT seem a little scant - there is BlueUtil, see How to control Bluetooth wireless radio from the command line? but that only appears to turn the BT on of off. However, bolting AppleScript on to the rest of the Arduino IDE control script quickly makes things more complex, although you could just put the Arduino command within the AppleScript, I guess.

You could use ESP-LINK to program the Arduino over WiFi.
The ESP8266 is simple cheap Wi-Fi MCU that can be programmed with Arduino IDE.
ESP-LINK is firmware for the ESP8266 that makes the ESP act like serial connection (USB) to Arduino.
The firmware can be found here at ESP-LINK ESP8266.

One can use something like this. It is a custom bootloader to update a Arduino's code via a NRF24L01+ radio module.*
*It only works under Linux machines.


text:
Why does my 16x2 LCD displays weird letters and can't insert key from keypad?
I'm a newbie on Arduino here, and this is my first project on 16x2 LCD, 4x4 keypad and others. So, the story is, after I uploaded the program for my group's Arduino alarm clock to the Arduino board, the LCD displays black boxes on the first row of the LCD. But after soldering the LCD pins again and connect the Vo to the 10k ohm potentiometer, the LCD can display the "welcome" part properly. This can be seen in the two pictures below.

However, after a while, there are weird letters appearing on the second row of the LCD, blinking from the first picture below to the second picture again and again. Plus, I couldn't input any key from the keypad to the LCD, since the display's stuck at there.

I'm not sure if there's any problem in the circuit or in the programming. I'm quite confused here. Below is the code I uploaded to the Arduino board. Thank you in advance.

#include <EEPROM.h>
#include <Keypad.h>
#include <DS1307.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <LiquidCrystal.h>

DS1307 rtc(SDA, SCL);
LiquidCrystal lcd(A3, A2, A1, A0, 5, 4);
Time t;

#define buz 3

int Hor, Min, Sec, h, m, s;
int ASCII = 48;
char* tim;
char* dat;
const char key = 0;
char buffer[2];
const byte numRows= 4;
const byte numCols= 4;
char keymap[numRows][numCols]=
{
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
byte rowPins[numRows] = {12, 11, 10, 9};
byte colPins[numCols]= {8, 7, 6, 5};
Keypad myKeypad= Keypad(makeKeymap(keymap),rowPins, colPins, numRows, numCols);

void setup() {
  Wire.begin();
  rtc.begin();
  pinMode(buz, OUTPUT);
  lcd.begin(16, 2);
  welcome();

  rtc.setDOW(SATURDAY); //Set Day-of-Week to SUNDAY
  rtc.setTime(10, 54, 0); //Set the time to 12:00:00     (24hr format)
  rtc.setDate(7, 1, 2017); //Day, Month, Year
}

void loop() {
  t = rtc.getTime();
  Hor = t.hour;
  Min = t.min;
  Sec = t.sec;
  tim = rtc.getTimeStr();
  dat = rtc.getDateStr();
  char key = myKeypad.getKey();

  if (key == 'C'){
    digitalWrite(buz, LOW);
    EEPROM.write(2, ASCII+6);
    EEPROM.write(3, ASCII);
  }

  if(key == '#'){
    lcd.setCursor(0,0);
    lcd.print("Enter New Time");
    lcd.setCursor(0,1);
    int j =0;
    int i=0;
    while( j<6)
    {
      if(i==2 || i == 5){
        lcd.print(":");
        lcd.display();
        i++;
      }
      key=myKeypad.getKey();
      if(key)
      {
        lcd.print(key);
        lcd.display();
        EEPROM.write(j,key);
        j++;
        i++;
      }
    }
  }

  changealarm();
  checkalarm();
  timedate();
}

void checkalarm(){
  if( Hor == h && Min == m)
  {
    delay(3000);
    lcd.setCursor(0,1);
    lcd.print("Hold C");
    digitalWrite(buz, HIGH);
    delay(3000);
  }
}

void changealarm(){
  buffer[0]=EEPROM.read(0);
  buffer[1]=EEPROM.read(1);
  h = atoi(buffer);
  buffer[0]=EEPROM.read(2);
  buffer[1]=EEPROM.read(3);
  m = atoi(buffer);
  buffer[0]=EEPROM.read(4);
  buffer[1]=EEPROM.read(5);
  s = atoi(buffer);
}

void timedate(){
  lcd.setCursor(0,0);
  lcd.print("Time: ");
  lcd.print(rtc.getTimeStr());

  lcd.setCursor(0,1);
  lcd.print("Date: ");
  lcd.print(rtc.getDateStr());
  delay(3000);
  lcd.setCursor(0,1);
  lcd.print("Alarm: ");
  lcd.print(h);
  lcd.print(".");
  lcd.print(m);
  lcd.print(".");
  lcd.print(s);
  delay(3000);
}

void welcome(){
  lcd.setCursor(0,0);
  lcd.print("Welcome");

  lcd.setCursor(0,1);
  lcd.print("To");
  delay(3000);

  lcd.setCursor(0,1);
  lcd.print("TIMeProject");
  delay(3000);
}

Which of the many DS1307 libraries are you using in paricular?

I use DS1307 library from this website http://www.rinkydinkelectronics.com/library.php?id=34

Only a beginner would try to make a full project work. An more experienced programmer makes a small part and test if it works, and then another part and so on. You could make a small sketch to test the buttons for example. A text has a zero terminator. Make your buffer 10 or 16 or 40, but not just size 2. Set buffer[2] to '\0' before calling atoi. The 'key' is printed on the display, I think that is what you see.

I've already changed the changealarm() code according to jose can u c's solution, but the weird letters are still there. What should I do?

In your changealarm() function, you call atoi(buffer), and buffer is defined as char buffer[2].
atoi() expects a c-style string, which is null-terminated, and you have to include space for the null termination character ('\0', 0, 0x00, etc.), but you write to both allocated spaces in the changealarm() function. If your 2nd byte of each EEPROM space (1, 3, 5) is non-zero, then your have an unterminated string.
atoi() expects a null-terminated string, and so the behavior is unexpected. Probably atoi() is running into other memory. If the string being sent is not representable by a int type, then the behavior of atoi() is undefined.

A quick fix would be to increase the size of buffer and guarantee null termination:
char buffer[3];  // Make the buffer 3 bytes long
[...]
void changealarm() {
  buffer[2]=0;   // Set the 3rd byte to zero to null-terminate

  buffer[0]=EEPROM.read(0);
  buffer[1]=EEPROM.read(1);
  h = atoi(buffer);
  buffer[0]=EEPROM.read(2);
  buffer[1]=EEPROM.read(3);
  m = atoi(buffer);
  buffer[0]=EEPROM.read(4);
  buffer[1]=EEPROM.read(5);
  s = atoi(buffer);
}

I see. But what's I'm supposed to do? Should I change the atoi() part? I'm a bit confused.

I updated my answer to show a solution to the overflow problem. (There are other problems in your code, too, like a lot of 3000ms delays where nothing can happen; not even keypad presses)

I've changed the changealarm() part according to your solution. And I've tried to change the delays to 1000ms. But still, the same display occurs. So, I'm guessing, there's something wrong at the if(key == '#') ... part?

How long after the sketch starts does the junk display occur? Does it occur if you press no keys at all?

After I changed the delays to 1000ms, the junk display occurs a second after the lcd.print("TIMeProject"); display. It keeps on blinking the junk display automatically. And yes, it occurs if I press no keys at all, right after I uploaded the code to the board.

The weird letters displayed problems are solved! It turns out that the keypad pins were connected differently with the code uploaded.


text:
Arduino Uno data logger shield recording nonsense time
I'm using an Arduino Uno with the Adafruit Data Logger Shield powered by a Voltaic 5V 2A battery pack. When writing to an SD card, the time stamp never changes (always reports the same now.unixtime). However, when powered from a laptop, the time stamp is correct and everything seems to be working.
The input voltage from the battery is confirmed to be just over 5V and not substantially lower the the laptop usb port.
Has anyone seen this before? Any ideas?

Where are you brining the power onto the Arduino board? If you bring it in through the external power connector you need to account for the voltage needed to run the regulator. You might be running into problems with low voltage and some part of your system that is sensitive to it.
You could try bring the power in on the 5 V pin, but then you are taking responsibility for the quality of the power supply.

The problem was indeed a question of voltage.
I was using the battery to supply 5 volts to the DC power port, which as suggested by the comments needs 7 volts or more. The problem is fixed by using the battery, which supplies a stable 5V, to give power to the USB port (or, presumably the 5V pin, though that is not available in my application).

If you are putting just over 5V into the Vin, it goes through the on-board regulator and needs a 7v minimum per https://www.arduino.cc/en/Main/ArduinoBoardUno  The Adafruit Data Logger Shield doc at https://learn.adafruit.com/downloads/pdf/adafruit-data-logger-shield.pdf shows a 9V battery pack.


text:
Serial Communication to Arduino with Node.js
I ran into some strange problems while trying to send data from my Node.js Server to my Arduino. My goal is to transfer an Int to the Arduino Nano and display it on a LCD. So far I managed to connect the server with the Arduino with the help of the serial library. The Arduino returns all data sent to it via Serial and prints it bytewise to the LCD.
These are the problems:

Node.js always opens the port, but is only able to send and receive data when the Serial Monitor from the Arduino IDE is opened.
The Data Node.js is sending seems to have a special format or gets transformed during the Process. If I send a simple int like 2, the display shows a y and an undecipherable character, and the data returned looks like this:  49 50 49 13 10 48 13 10. I noticed that the amount of 13 corresponds with the int I send (3 send = three 13's come back). When I enter data into Arduinos own Serial Monitor, it is displayed correctly and returned as ASCII (because I am saving the return value of Serial.read() as an Int).

Here's my server (the relevant parts):

http = require('http');
fs = require('fs');
serialport = require('serialport');

port = 3000;
host = '127.0.0.1';
SerialPort = serialport.SerialPort;
arduinoPort = '/dev/ttyUSB2';

var printLog = true;
var playerRoundKills = 0;
var playerTotalKills;
var roundLive = false;

//open port
var myPort = new SerialPort(arduinoPort);
parser: serialport.parsers.raw          //rohdatenparser definieren
serialport.on('open', function(){
  console.log('Serial Port Opend');
  serialport.on('data', function(data){
      console.log(data[0]);
  });
});

//implementation of abstract port functions
myPort.on('open', showPortOpen);
myPort.on('data', sendSerialData);
myPort.on('close', showPortClose);
myPort.on('error', showError);

function showPortOpen() {
   console.log('port open. Data rate: ' + myPort.options.baudRate);
}

//output incoming data
function sendSerialData(data) {
   console.log(data[0]);
if(typeof data[1] !== 'undefined') console.log(data[1]);
}

function showPortClose() {
   console.log('port closed.');
}

function showError(error) {
   console.log('Serial port error: ' + error);
}

myPort.on("open", function () {
  console.log('open');
//send data (3) to arduino
myPort.write(3, function(err, results) {
    if(err != null)console.log('Fehler beim ersten senden: ' + err);
    if(results != null)console.log("Killcount erstmals gesendet: "+results);
  });
});

And my sketch:
#include <LiquidCrystal.h>

//LDCD Display
LiquidCrystal lcd(9, 8, 6, 5, 4, 3);  //Digitale Pins an dem das Display angeschlossen ist
#define LCD_WIDTH 16                    //Anzahl Spalten des Display (16)
#define LCD_HEIGHT 2                    //Anzahl Zeilen des Display (2)

#define DEBUG_MODE true

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

  lcd.begin(LCD_WIDTH, LCD_HEIGHT,1);

  lcd.setCursor(0,0);

}

void loop() {
  // when characters arrive over the serial port...
  if (Serial.available()) {

    //clear display for new killcount
    //lcd.clear();
    // wait a bit for the entire message to arrive
    delay(100);
    // read all the available characters
    while (Serial.available() > 0) {
      // write each character to display as ascii
    int temp = Serial.read();
    lcd.write(temp);
    Serial.println(temp);

    }
    //Serial.flush();
  }
}

I'd appreciate any suggestions! =)

49 50 49 13 10 48 13 10 are ascii codes for :
"1" "2" "1" CR LF
"0" CR LF does that give you a clue ?

I solved that by passing the data in a Buffer. The connection only works when the arduino terminal is opened though.


text:
Reading values from TTP229 capacitive touch sensor on arduino
I would like to be able to read the raw capacitive sensor values from a TTP229 chip through i2c in Arduino. I have one of these breakout boards to play with :

My goal is to get values similar to those of the MPR121 or the Capacitive Sensor Arduino library where the reading changes depending on proximity and how hard you touch the pads. I have tested the following code but I'm only able to detect an on / off reading.
#include <Wire.h>
#define ttp229 ( 0xAF>>1 )

uint16_t data_out = 0;
uint16_t data1, data2;
int count = 0;
boolean count2 = false;
int button[16];
int oldata[16];

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

void loop()
{
    Wire.requestFrom( ttp229, 2, true );
    //delay(1);
    while( Wire.available() )
    {
        data1 = Wire.read();
        data2 = Wire.read();
        data_out = (data1<<8)|data2;

        for(int i=1;i<17;i++)
        {
            uint16_t contrast = 0x8000;
            if(data_out & contrast)
            {
                //Serial.println(i);
                button[count]=i;
                count++;
            }
            data_out<<=1;
        }
        if(count2)
        {
            switch(count)
            {
                case 1:
                if( oldata[0] == button[0] )
                {
                    Serial.println( button[0] );
                    delay( 20 );
                }
                break;
                case 2:
                if(oldata[0]==button[0]&&oldata[1]==button[1])
                {
                    for(int i = 0; i < 2; i++)
                    {
                        Serial.print( button[i] );
                        Serial.print("  ");
                    }
                }
                break;
            }
        }
        for( int i = 0; i < 16; i++ )
        {
            oldata[i] = button[i];
        }
        count = 0;
        count2 =! count2;
    }
}

Even if i just print out data1 and data2 from the example it doesn't seem to produce readings that change with the capacitance. I originally thought this was a hardware limitation but then I came across this TTP229 product that has a linear touch sensor built into it.
Does anyone have any experience with this sensor and how I can access the raw readings?

I am afraid, the product you referenced seems to have 8 discrete pads underneath the slider. So I suppose, they really read out those 8 steps only. Check the images that show the device from the bottom side. This doesn't answer your question directly, but I still hope it helps.

mpr121 gives raw values
it has 12 electrodes/capacitance sensing inputs
https://www.sparkfun.com/datasheets/Components/MPR121.pdf
https://github.com/BareConductive/mpr121/tree/public/MPR121/Examples/DataStream

Thank you, but this is not an answer. My question is about reading raw values on the TTP229 not on the MPR121.


text:
esp8266 esp-01 printing garbage values on serial monitor
I am trying to up an esp8266 esp-01. While monitoring the serial monitor it's printing garbage values. I am using arduino-mega to write the code to the esp8266. The sample code i'm trying to write is
#include <ESP8266WiFi.h>
const char* ssid     = "SSID";
const char* password = "PASSWORD";

void setup() {
  Serial.begin(9600);// tried other rates as well
  delay(10);
  Serial.println('\n');

  WiFi.begin(ssid, password);
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  int i = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(++i); Serial.print(' ');
  }

  Serial.println('\n');
  Serial.println("Connection established!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());
}

void loop() { }

Before this I tried to test the esp with a blink program, and it seems working. The connections between esp and arduino are as below
Arduino | ESP
------------------------------------------------------------
3.3V    | VCC(through a button)
3.3V    |CH_PD
TX      | TX
RX      | RX (connected through a voltage divider to arduino)
GPIO 0  | GND (through a push button to GND)
GPIO 2  | 3.3V (through a 1K resistor to 3.3V)

Arduino's the RESET and GND are shorted. What I'm trying to achieve to make the wifi module to act as message que, sending and receiving data to and from a device which is connected to it via internet.

I suspect it's boot-looping due to lack of power and you're seeing the ESP8266 boot messages.

The "garbage values" are most likely messages from the bootloader, output at 74880bps. Try watching its serial out at that speed. You'll probably see messages that look something like:
ets Jan  8 2013,rst cause:2, boot mode:(3,7)
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d

The rst cause number will give you an indication of why the chip rebooted.
The most common reset causes are

power on
hardware watchdog timer
fatal exception (most likely error in your code or power issue)
software watchdog timer
software reset
deep sleep
hardware reset

If it's a "fatal exception", you should see another line that looks like this:
Fatal   exception   (28):
epc1=0x4025bfa6,    epc2=0x00000000,    epc3=0x00000000,    excvaddr=0x0000000f,
depc=0x00000000

Look up the exception number; if it's not obvious what it means, google it to learn about the causes.


text:
Programming Leonardo with TTL to USB cable
I have wired my Arduino as seen in the picture, with the RX of the cable plugged into the TX (D1) of the Leonardo and the TX of the cable plugged into the RX(D0) of the Leonardo. I then have the ground plugged into GND and the power into 5V. The driver is installed correctly and the IDE recognizes the port, however, whenever I try and upload any sketch, I get the error:
Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader
Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
I can upload sketches fine via usb, is it just unable to do so via a USB to TTL cable?

Thanks in advance

The bootloader on the Leonardo operates through the native USB port of the ATMega32U2 chip, not the UART.
You cannot treat it like an Uno because it isn't an Uno.
You can only program it through the USB port or through the ICSP connector.
If you want to use UART to upload you will need to replace the bootloader with a suitable UART based alternative. (Before you ask, no I don't know if one even exists or where to get it if it does).

That would make sense. I am assuming that the Leonardo can still communicate with other serial devices via the UART correct? I am not very familiar with bootloaders, hence my ignorance...

Yes, that is down to the sketch, not the bootloader.


text:
MQTT for GSM/GPRS sheild
I want to publish sensor data to server using MQTT protocol via GPRS/GSM modem.
I googled MQTT for Arduino, AQTT Arduino available only for Ethernet shield or will MQTT Arduino Ethernet shield work in GSM modem?

Arduino MQTT Library for SIM800 (and SIM900) GSM Modem is available at ElementzTechBlog, ElementzGithubRepository
Functionalities:
Auto connect

Automatically connect to TCP and to MQTT server.

connect function

This function can be used to connect your client to MQTT broker.
Use only if you do not use Auto connect functionality.
Optionally  you can use username, password, WILL topic and WILL
Message.

OnConnect CallBack function

This call back function is called when MQTT connection is
established.
You can call subscription and publish functions inside it (according to your need).

publish function
 - This function can be used to publish messages to different topics.

You can select  QoS levels and RETAIN flag according to your need.

subscribe function

This function can be used to subscribe messages from different
topics.

OnMessage CallBack function

This callback function is called when messages are received from
subscribed topics
Topic, TopicLength, Message, MessageLength are the arguments of
OnMessage callback function.
Inside this, you can write your custom code.

unsubscribe function

This function can be used to unsubscribe from a previously subscribed
topic.

disconnect function

This function can be used to disconnect your client from MQTT broker.

Keep Alive

You can specify your KeepAlive duration while initializing.
Ping requests are sent and received automatically.

Subscribe Publish examples are also provided.

Nick O'leary published an MQTT client for Arduino.
I use it extensively.  You can find it here: http://knolleary.net/arduino-client-for-mqtt/.
Once you have established a tcpip connection you can use this library to send/receive via the MQTT protocol across a GPRS/GSM modem.  I have used it successfully on:

the Arduino GSM shield
the Seeeduino GPRS IoT panel
a Freetronics Arduino Mega connecting via ethernet to a TPLink MR3020 router

Do you have an example for the GSM shield?


text:
Arduino WiFIWebSever - why client.println()?
I need to modify the WiFiWebServer example on the Arduino website but I am having some trouble understanding the code. I am hoping to get some advice from the community on the client-server relationship in this example so I can better modify it to suit my needs.
The problem I am having is the jump between server commands and client commands. Initially I see server commands; server.begin() in setup and server.available() in the loop. The commands quickly shift, however, as nearly all the other commands in the loop become client.println()'s.
I understand the initial client commands that deal with whether the client is available and whether it is still connected. The part I don't understand, however, are the client.read and client.println commands. Even client.read makes some sense to me since I want some communication from the client side but why does the example use client.print? The Arduino webpage defines the WiFiClientPrintln as data you write from the client to the server that it is connected to. Wouldn't I want to use server.print since the Arduino in this example is the server and the client is the computer I use to view the webpage that I built on the server?
I am using the WiFIWebServer example as a template for my project. The goal is to have the Arduino take sensor readings and post them on a webpage it hosts by acting on the server. This is quite similar to the example but I notice that I have slow update/transmission speeds and errors when a different client connects to the server. For example, if I view the website on my computer, I get the data fairly consistently If somewhat slow. If I try to view the same website off my mobile device, however, I have problems connecting, may need to refresh several times and the webpage crashes on the computer.
I am trying to troubleshoot the issue but going through the code I can't figure out the reason for the client.println()'s instead of server.println(). Even if that isn't the cause of my multi-client issue, I would like a better understanding of the code before going forward so would appreciate any guidance you can provide.

The confusion you have arises from the context of the command.
The server.* commands manipulate the server instance - that is, the actively listening socket that is waiting for connections.
The client.* commands change their meaning depending on if you are a server waiting for connections or a client that is making a connection.
In the latter case client.print() sends data to the server.
In the former case, on a server, the client.* commands refer to a specific client that has made a connection to the server.  Using client.print() in this instance sends data to the currently connected client.
So "client" can be thought of as "the connection between me and the remote end" however that connection was created - either by "me" specifically connecting to the remote end, or the remote end connecting to my "server" instance and a new "client" being spawned from it for this one connection.
Remember - a client can only connect to one server, but a server can have many connections from many different clients, and it is those client connections that you talk to.

client.println() is sending data to a specific client.
server.println() is sending data to every client that is connected to the server.
Also, i believe that the arduino keeps sending data to the client instead of stopping the request. You should have some javascript that updates the value say... every 5 seconds or so... Or you could have a
<meta http-equiv="refresh" content="5">

inside the  part which would tell the browser to refresh the page every 5 seconds instead of using the header
See http://tentencraft.net/demo1.php vs http://tentencraft.net/demo2.php

Thank you for the response and the suggestions.
I initially assumed the same about sending data to every client and refreshing but it does not produce the desired effect. I set updates to every second but it feels like it takes something like 30s updating on the computer and even worse on a mobile device. I have to force the mobile device's reload more often than not.
To circle back to the server.println(), if that is the command that sends data to every client on the server, wouldn't that make it the one to use for multi-client setups. Would client.read/available be affected?
Thanks again

@DaveP, forgive me for not following the proper forum etiquette but I am not able to upvote until I have 15 rep. While the reply was useful, my question has not yet been answered since I still don't understand why a WiFiWebServer example would use a client.print versus a server.print.

You would want to refresh it instead of sending more data unless you want it to keep logging the temperature to the client. If you add refresh code to the top then close the connection it will update the web page every x seconds.

@user3303997 my code, which follows the Arduino WebServer example, includes two lines "Connection: close" and "Refresh : 1". Based on the example notes, this means that it closes the connection after the completion of the response and refreshes every second. Despite the setting, the refresh rate is nowhere near 1 second - do I need to close the connection in Arduino code? I thought the http code was sufficient.

I suggest using the meta refresh i posted above and close the connection in arduino.


text:
Can I replace Atmega8 with Atmega328 in my freeduino board?
Can I replace Atmega8 with Atmega328 in my freeduino board?
If so, let me know the steps needed.

Shouldn't be a problem. Some later versions already have a ATMega168 instead of the ATMega8. All three are pin-compatible.
In the arduino IDE you should however select a different board (one with a 328, like the UNO). That way the compiler knows the target MCU is the 328, and not the 8.

Not all registers are the same though. But the arduino platform takes care of these difference for you.


text:
How to read pinMode for digital pin?
Is there a way for me to read the pin mode for one of the digital pins on Arduino?   In other words, can I determine whether a pin's been set to an input or output?

Yes, you can use the data direction registers (DDRB, DDRC, DDRD depending on which port) to check what mode a pin is in.
If a pin is in output mode then the corresponding bit in DDRx will be 1.
One complication is that the Arduino functions give each pin an "Arduino" pin number, and you have to look at a pin map to figure out which DDR register and bit corresponds to the pin you want to check. You can find a pin map for Arduinos based on the ATMEGA168/ATMEGA328 (including Uno) here...
https://www.arduino.cc/en/Hacking/Atmega168Hardware
So, for example, if you want to check if Arduino digital pin #4 is set for output, you'd look at the map and see that corresponds to PD4. That means "port D" and "bit 4", so you could say...
if ( DDRD & _BV(4) ) {   // Check bit #4 of the data direction register for port D
    // If we get here, then Arduino digital pin #4 was in output mode
} else {
    // If we get here, then Arduino digital pin #4 was in input mode
}

If you want to check Arduino digital pin #14, then you would use DDRB & _BV(5).
(_BV(x) is a macro that shifts 1 x bits to the right.)

Seems like the Arduino core is missing a function to read the pinMode(). Here is a possible implementation:
int pinMode(uint8_t pin)
{
  if (pin >= NUM_DIGITAL_PINS) return (-1);

  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *reg = portModeRegister(port);
  if (*reg & bit) return (OUTPUT);

  volatile uint8_t *out = portOutputRegister(port);
  return ((*out & bit) ? INPUT_PULLUP : INPUT);
}

It handles illegal pin numbers (return -1), and all pin modes; OUTPUT, INPUT and INPUT_PULLUP.
Cheers!
BW: I have added this as an issue on the Arduino github repository.

Nice solution. They should add it to the standard.

There are functions which can get you the registers and bit numbers from a pin number built into the Arduino API.
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
volatile uint8_t *reg = portModeRegister(port);

if (*reg & bit) {
    // It's an output
} else {
    // It's an input
}

This answer is also right and I will be using these functions in the future. Thanks for pointing them out!

authors: Серго Селиванов


text:
Connecting and Programming LinkSprite Camera to Arduino
I recently bought the LinkSprite color jpeg camera:
https://www.sparkfun.com/products/12804
And the Arduino Wireless SD Shield:
https://www.arduino.cc/en/Main/ArduinoWirelessShield
I was wondering how to connect the camera to the Arduino and how to have it take and save a picture to the sd card when a button is pressed.

What type of Arduino? The camera requires serial communication. HardwareSerial would be a good idea but that would require a Mega or Leonardo etc (board with extra serial ports). SoftwareSerial is possible but difficult to get to work at higher speed.

its an Arduino Uno r3

i have a mega also if i need that

What have you done so far to try this yourself?

Nothing really, i have been looking around to figure out how to connect it

Connect the camera to a serial port (hardware or software serial depending on Arduino board). See further information on wiki.
Control the camera and fetch the image over the serial connections (see commands) and write to the SD disc.