texts:
I'm working on my first arduino project, Sumo Robot, therefore i dont know much about programming yet.  We are supposed to use two IR sensors one on the front of the robot other on its back to avoid crossing the black line of the arena.
I wrote this simple code to control the motors.
But i have been  asked to use interrupts to raise the efficiency of my code.

So do you guys have an idea of how i can use interrupts with the L298n motor driver to move my dc motors forward and backward.

Here is my code

int fIR=7;
int bIR=8;
int fIR_value;
int bIR_value;
const int trigPin = 9;
const int echoPin = 11;

long duration;
int distance;

int IN1 = 4;
int IN2 = 5;
int IN3 = 6;
int IN4 = 12;

void setup() {
  Serial.begin(9600);
  pinMode(fIR,INPUT);
  pinMode(fIR,INPUT);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  pinMode(IN1,OUTPUT);
  pinMode(IN2,OUTPUT);
  pinMode(IN3,OUTPUT);
  pinMode(IN4,OUTPUT);

}

void loop() {

  fIR_value = digitalRead(fIR);
  Serial.print("Front IR:");
  Serial.print(fIR_value);
  Serial.print(" , ");

  bIR_value = digitalRead(bIR);
  Serial.print("Back IR:");
  Serial.print(bIR_value);
  Serial.print(" , ");

  digitalWrite(trigPin, LOW);
  delayMicroseconds(10);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration*0.034/2;
  Serial.print("Distance: ");
  Serial.println(distance);
  delay (500);

  if(distance<30&&fIR_value==HIGH&&bIR_value==LOW){
    STOP();
    delay(50);
    BACKWARD();
//    Serial.print("1");
  }
  else if(distance<30&&fIR_value==LOW&&bIR_value==HIGH){
    STOP();
    delay(50);
    FORWARD();
//    Serial.print("2");

  }
  else if(distance<30&&fIR_value==LOW&&bIR_value==LOW){
    STOP();
    delay(50);
    FORWARD();
//    Serial.print("3");

  }
    else if(distance>30&&fIR_value==LOW&&bIR_value==LOW){
    STOP();
    delay(50);
    ROTATE();
//    Serial.print("4");

  }
   else if(distance>30&&fIR_value==HIGH&&bIR_value==LOW){
    STOP();
    delay(50);
    BACKWARD();
//    Serial.print("5");

  }
   else if(distance>30&&fIR_value==LOW&&bIR_value==HIGH){
    STOP();
    delay(50);
    FORWARD();
//    Serial.print("6");

  }
}

void FORWARD(){

  digitalWrite(IN1,200);
  digitalWrite(IN2,0);
  digitalWrite(IN3,0);
  digitalWrite(IN4,200);
}
void BACKWARD(){

  digitalWrite(IN1,0);
  digitalWrite(IN2,200);
  digitalWrite(IN3,200);
  digitalWrite(IN4,0);
}
void ROTATE(){

  digitalWrite(IN1,200);
  digitalWrite(IN2,0);
  digitalWrite(IN3,200);
  digitalWrite(IN4,0);
}
void STOP(){

  digitalWrite(IN1,0);
  digitalWrite(IN2,0);
  digitalWrite(IN3,0);
  digitalWrite(IN4,0);
}


texts: Is there possible implement websocket using AT Command?

texts:
For example I have a sim800l module to communicate to a server using websocket (socket.io) but that module allows AT Command to operate.

I have successfully made an HTTP request, but I don't know how to make a request via WebSocket using AT Command.

thank you.


texts: Convert ASCII output to human readable form and assign to a variable

texts:
I'm reading the RFID output and I can print it to the serial monitor as human readable. But what I want is to assign that to a variable. But I'm getting the ASCII. Is there any way to convert it and get to the variable like Serial.write() do.

byte readbackblock[19];

for (int j=0 ; j<16 ; j++)//print the block contents
    {
      Serial.write (readbackblock[j]);
      cardNumber += readbackblock[j];
    }

Serial.print(cardNumber);

Serial output

read block: 1234567890123456

49505152535455565748495051525354

Any help please.


texts: Math with analog input values coming out wrong

texts:
Im getting stuck in a while loop because Im having trouble running a calculation on some sensor values. When I read my four sensors values and compare the ratio of the first two to the second two, I keep getting 0.00, no matter what the values are. Here's my code:

while ( ( (frontleft + frontright) / (backleft + backright) <= 0.8 ) || ( (frontleft + frontright) / (backleft + backright) > 1.2) ) {
    if (backleft + backright > frontleft + frontright) {
      myStepper2.step(10);
    }
    if (backleft + backright < frontleft + frontright) {
      myStepper2.step(-10);
    }
    int backleft = analogRead(A0);
    int backright = analogRead(A1);
    int frontleft = analogRead(A2);
    int frontright = analogRead(A3);

    Serial.print("Backleft Reading: ");
    Serial.println(backleft);
    Serial.print("\n");
    Serial.print("BackRight Reading: ");
    Serial.println(backright);
    Serial.print("\n");
    Serial.print("Frontleft Reading: ");
    Serial.println(frontleft);
    Serial.print("\n");
    Serial.print("Frontright Reading: ");
    Serial.println(frontright);
    Serial.print("\n");
    float ratio = (frontleft + frontright) / (backleft + backright);
    float math = (5 + 6) / (4 + 5);
    Serial.print("Math: ");
    Serial.println(math);
    Serial.print("Ratio: ");
    Serial.println(ratio);
    Serial.print("\n");
    delay(500);

  }

Im getting values for my sensors (backleft, backright, frontleft, frontright), but 'ratio' always comes out 0.00. Because of that, Im getting trapped in the loop I believe. What's going on here?

Also, just to check, I added 'math' float as that quick calculation, but I'm getting a value of 1.00 in Serial Monitor. Why? It should be 1.222.


texts: uno + ethernet sheild(wiznet) + dh22 temp humidity sensor + viewing data online

texts:
i am new to arduino and have no experience with programming

i have an uno r3 board, a wiznet ethernet sheild, and dh22 temp and humidity sensor.

  I would like to have it update plot.ly to view the data.

error returned on monitor is ...

POST /clientresp HTTP/1.1
Host: plot.ly:80
User-Agent: Arduino/0.6.0
Content-Length: 340

version=2.3&origin=plot&platform=arduino&un=jozef.jones&key=tgcio4brx1&args=[{"y": [], "x": [], "type": "scatter", "stream": {"token": "ke1f6fwqas", "maxpoints": 100}}, {"y": [], "x": [], "type": "scatter", "stream": {"token": "k5lmga9qrl", "maxpoints": 100}}]&kwargs={"fileopt": "overwrite", "filename": "filename", "world_readable": true}
... Sent message, waiting for plotly's response...
HTTP/1.1 200 OK
Content-Type: application/json
Date: Sun, 17 Jan 2016 16:22:32 GMT
Server: nginx/1.8.0
Set-Cookie: csrftoken=WknqVtPqjTYvlTyoKSC5QehqDgmt7Qp7; expires=Tue, 17-Jan-2017 16:22:32 GMT; Max-Age=31622400; Path=/; secure
Set-Cookie: anoncsrf=2UDFDiQhQq1zf5MIMaoRJ0ayaqs7g58R; expires=Mon, 18-Jan-2016 16:22:32 GMT; httponly; Max-Age=86400; Path=/
Vary: Accept-Encoding
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Content-Length: 138
Connection: keep-alive

{"url": "", "message": "", "warning": "", "filename": "", "error": "Missing required POST parameters: platform un key origin args kwargs"}

code is

#include <SPI.h>
#include <Ethernet.h>
#include "plotly_streaming_ethernet.h"
#include "DHT.h"

#define nTraces 2

char *tokens[nTraces] = {"ke1f6fwqas", "k5lmga9qrl"};
// arguments: username, api key, streaming token, filename
plotly graph("jozef.jones", "tgcio4brx1", tokens, "filename", nTraces);

// DHT Sensor Setup
#define DHTPIN 2 // We have connected the DHT to Digital Pin 2
#define DHTTYPE DHT22 // This is the type of DHT Sensor (Change it to DHT11 if you're using that model)
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT object

byte mac[] = { 0x00, 0xAA, 0xBB, 0x00, 0x00, 0xCC };
byte my_ip[] = { 192, 168, 1, 117 }; // google will tell you: "public ip address"

void startEthernet(){
    Serial.println("... Initializing ethernet");
    if(Ethernet.begin(mac) == 0){
        Serial.println("... Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, my_ip);
    }
    Serial.println("... Done initializing ethernet");
    delay(1000);
}

void setup() {
  graph.maxpoints = 100;
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  startEthernet();

  bool success;
  success = graph.init();
  if(!success){while(true){}}
  graph.openStream();
  dht.begin();
}

float h, t;

void loop() {
      h = dht.readHumidity();
      t = dht.readTemperature();
      graph.plot(millis(), t, tokens[0]);
      graph.plot(millis(), h, tokens[1]);
}


texts: Sending and receiving custom messages with Ardulink

texts:
I am sending custom code to Arduino with this ardulink command:

{        ArduinoControl.link.sendCustomMessage("oled");
}

Code from standard Ardulink sketch CustomMessagesChipKit.ino:

{
  if (stringComplete) {
    if(inputString.startsWith("alp://")) {
    // OK is a message I know (this is general code you can reuse)
      boolean msgRecognized = true;
      if(inputString.substring(6,10) == "cust") { // Custom Message
        // here you can write your own code.
        int separatorPosition = inputString.indexOf('/', 11 );
        int messageIdPosition = inputString.indexOf('?', 11 );
        String customId = inputString.substring(11,separatorPosition);
        String value = inputString.substring(separatorPosition + 1, messageIdPosition);
        if(customId == "oled") {
            //Clear the virtual buffer
            lcd.noBacklight();
            analogWrite(9,100);
            digitalWrite(13, HIGH);
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("jkhgvjgv");
        } else {
          msgRecognized = false;
          // this sketch doesn't know other messages in this case command is ko (not ok)
        }
      } else {
        msgRecognized = false;
        // this sketch doesn't know other messages in this case command is ko (not ok)
      }
      // Prepare reply message if caller supply a message id (this is general code you can reuse)
      int idPosition = inputString.indexOf("?id=");
      if(idPosition != -1) {
        String id = inputString.substring(idPosition + 4);
        // print the reply
        Serial.print("alp://rply/");
        if(msgRecognized) { // this sketch doesn't know other messages in this case command is ko (not ok)
          Serial.print("ok?id=");
        } else {
          Serial.print("ko?id=");
        }
        Serial.print(id);
        Serial.write(255); // End of Message
        Serial.flush();
      }
    }
    // clear the string:
    inputString = "";
    stringComplete = false;
  }}

As a result the LED on pin 13 is turning on after message from java program. But that is all. LCD or or LED on PWM 9 pin are not reacting at all.

Also I could not understand how to send an answer back from Arduino to Ardulink. Can you please show me an example? I would love to send and print data in Java program from  DHT11 sensor in response. I know about RawDataListener and I read the whole Ardulink site, but I did not understand that. I a newbie in programming.

When i replace

{String customId = inputString.substring(11,separatorPosition);}

with

{String customId = inputString.substring(11,15);}

than everything works. What can it be?


texts:
I am working on ESP8266 and I want to send a GET request with AT command to my localhost but I failed every time. Can you help me solve this problem please? Thank you for interest!
I attached my terminal code and my code:

#define ag_ismi "SUPERONLINE_WiFi_8022"
#define ag_sifresi "rC5YGNYebuCf"
#define IP "192.168.1.9"

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

  Serial.begin(115200);
  Serial.println("AT");
  delay(3000);
  if(Serial.find("OK")){
    Serial.println("AT+CWMODE=1");
    delay(2000);
    String baglantiKomutu=String("AT+CWJAP=\"")+ag_ismi+"\",\""+ag_sifresi+"\"";
    Serial.println(baglantiKomutu);
    delay(5000);
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(60000);
  Serial.println("AT+CIPMUX=1");
  Serial.println("AT+CIPSTART=\"TCP\",\"192.168.1.9\",8000");
  delay(1000);
  String model = "GET /kanbanDB/arduino?model=1 HTTP/1.1";
  //model+="Host: 192.168.1.9:8000\r\n\r\n";
  model+="r\n\r\n";
  Serial.println("AT+CIPSEND=" + String(model.length()));
  Serial.println("\r\n\r\n");
  delay(1000);
  Serial.println(model);
  Serial.println("\r\n\r\n");
  delay(1000);
  Serial.println("");
}


texts:
I am a beginner with Arduino. I am doing something to cool down my room temperature using an exhaust fan and cooler through relays. I am trying to reduce the temperature initially using an exhaust fan and wait for 10 minutes to see if the temperature reduced to a set range. If not, the exhaust fan is turned off and the rest of the cooling is done by the cooler.

At the beginning of the program all goes well: it turns on the exhaust fan and waits 10 minutes and if it's not dropping, it transfers the job to the cooler. But after one cycle, when the temperature increases, the cooler is turned on directly, without the exhaust fan urning on, or waiting for 10 minutes and things. I tried a lot but I can't understand what is happening. Please suggest something to solve the problem.

#include <dht.h>

dht DHT;

#define DHT1_PIN 7 // dht11 connected to pin 7

int exhaustpin = 4; // set pin for exhaust fan relay
int coolerpin = 5; // set pin for cooler relay
boolean exhaust;
void setup(){
   Serial.begin(9600);
    pinMode(exhaustpin, OUTPUT);
  pinMode(coolerpin, OUTPUT);
  digitalWrite(exhaustpin,HIGH );
  digitalWrite(coolerpin,HIGH );
  exhaust= LOW;

}
void loop()
{

    DHT.read11(DHT1_PIN);
  Serial.print(" MY Room Temperature = ");
  Serial.println(DHT.temperature);
  Serial.print("MY Room Humidity = ");
  Serial.println(DHT.humidity);
 delay(500);
  int  roomtemp =DHT.temperature;
  static unsigned long interval;
  long interval;
  if (exhaust== LOW){
  if ((roomtemp>=30)&&(digitalRead(coolerpin)==HIGH )){
    digitalWrite(exhaustpin,LOW ); // if temperature increses above 30 the exhaust starts to work
     interval = millis();
  }
  }
   if (digitalRead(exhaustpin)==LOW){
     exhaust= !exhaust;
 if ((millis()-interval) >= 600000){
    digitalWrite(coolerpin,LOW );
    digitalWrite(exhaustpin,HIGH );   // after the starting of exhaust fan it wait for 10 minutes ,then it turn
                                      // on the cooler and turns off the exhaust fan
       }
   }
  if (roomtemp<28){
    digitalWrite(coolerpin,HIGH );
     digitalWrite(exhaustpin,HIGH );
     exhaust= !exhaust;
   // i am trying here to start cooling the room with my exhaust fan
   // then wait 10 minutes ,if it is still not less than 28 degrees turn on the cooler to do the cooling
   // and turn off the exhaust fan
   }
  }


texts: Why do I need to include libraries used in other libraries?

texts:
I have a simple library which uses another library.

Here is the header:

#ifndef __DERIVEDCLASS_H__
#define __DERIVEDCLASS_H__

#include <HardwareSerial.h>

class DerivedClass
{
private:
    HardwareSerial* serial;

public:
    DerivedClass();
};
#endif

And the CPP:

#include "DerivedClass.h"

DerivedClass::DerivedClass()
{

}

And the sketch:

#include <DerivedClass.h>

void setup()
{
}

void loop()
{
}

This works fine.

However, if I change the library header to this:

#ifndef __DERIVEDCLASS_H__
#define __DERIVEDCLASS_H__

#include <SoftwareSerial.h>

class DerivedClass
{
private:
    SoftwareSerial* serial;

public:
    DerivedClass();
};
#endif

The sketch fails to compile:

  /Users/andrew/Documents/Arduino/libraries/DerivedClass/DerivedClass.h:9:
  error: ISO C++ forbids declaration of 'SoftwareSerial' with no type
  /Users/andrew/Documents/Arduino/libraries/DerivedClass/DerivedClass.h:9:
  error: expected ';' before '*' token

If I change the sketch to:

#include <DerivedClass.h>
#include <SoftwareSerial.h>

void setup()
{
}

void loop()
{
}

i.e. including the SoftwareSerial library in the top level sketch, it compiles fine.

If I expand the library out so it actually performs actions, then if it compiles, it works.

Why is this? HardwareSerial is a built-in part of the Arduino, located in hardware/arduino/cores/arduino and SoftwareSerial is in libraries, but why would the build process differentiate between the two.


texts: How can I increase the torque or speed of the stepper motor with Arduino

texts:
I run 28BYJ-48 12 Volt Motor with ULN 2003 Driver using Arduino UNO.
I am also using external 12 volt power outside.
I aim for the syringe pump to move back and forth with the rotation of the motor.
I'm using the code below.
The code is running but the motor cannot move the syringe back and forth.
How do I change to be able to move the syringe pump
const int motorPin1 = 8;
const int motorPin2 = 9;
const int motorPin3 = 10;
const int motorPin4 = 11;

int bekleme =2
;
// bekleme süresini değiştirerek step motorun hızlı veya yavaş ilerlemesini sağlayabilirsiniz.
//1sn=1000

void adim1() {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim2() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim3() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim4() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
delay(bekleme);
}

void setup() {

pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);

}

void loop() {

for (int i = 0; i < 2048 ; i++)
{
adim1();
adim2();
adim3();
adim4();
}
{

exit(0);
}
}

İleri
// Meraklı Mühendis Sayfasının hazırlığı kodlar kullanılmıştır.
//Dilerseniz farklı fonksiyonlar kullanabilirsiniz.

const int motorPin1 = 8;
const int motorPin2 = 9;
const int motorPin3 = 10;
const int motorPin4 = 11;

int bekleme =2;
// bekleme süresini değiştirerek step motorun hızlı veya yavaş ilerlemesini sağlayabilirsiniz.
//1sn=1000

void adim1() {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim2() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim3() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim4() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
delay(bekleme);
}

void setup() {

pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);

}

void loop() {

for (int i = 0; i <2048; i++)   // buradaki 512 değerleri step motorun tam bir tur dönmesini sağlıyor. dilerseniz bu sayıyı değiştirebilirsiniz
{
adim4();
adim3();
adim2();
adim1();

}
{

exit(0);
}
}


texts: How do I split a number into individual digits?

texts:
How would I split part1 into 2-3 digits and put them into num1, num2, and num3?

int FMSTATION = 10250;

int update_display() {
  int fm_station = FMSTATION ;

  int part1;
  int part2;

  part1 = (FMSTATION / 100);
  part2 = (FMSTATION % 100);
  part2 = (part2/10);

  int num1 = ;
  int num2 = ;
  int num3 = ;
  int num4 = part2;

  matrix.writeDigitNum(0, num1, false);  //1st number on lcd
  matrix.writeDigitNum(1, num2, false);  //2nd number on lcd
  matrix.writeDigitNum(3, num3, true);   //3rd number on lcd and adds "."
  matrix.writeDigitNum(4, num4, false);  //4th number on lcd

  matrix.writeDisplay();
}

I have searched the web from top to bottom, but could not find the answer. In the end what I should get displayed on my LCD is 102.5.


texts: Is it bad to power a arduino mega with 6V via USB?

texts:
I'm working on a project where there is no external 5V voltage regulator available but only 6V. I can not power it through the power jack because via this way I do not have enough current and get thermal shutdown.
Can I power it via 6V over USB? at the moment I'm trying this out and it works but what are the long term risks I'm prone to?


texts: How can you have two blinking leds and a fading one

texts:
I am trying to make a alarm and I have two blinking leds (red and blue). They work fine but I want two more that fade in and out.

I have a buzzer on it too.

I am very new to programming. By the way, the code below runs with no errors; just does not do what its intended to.

int led = 9;
int brightness = 0;
int fadeAmount = 5;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  delay(200);
  digitalWrite(11, LOW);
  delay(200);

  digitalWrite(12, HIGH);
  delay(200);
  digitalWrite(12, LOW);
  delay(200);

 digitalWrite(led, brightness);

 brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 delay(30);
}


texts: HC-06 Bluetooth module and slow communication

texts:
I'm communicating from an Android command line Bluetooth app interface to my Arduino. The Arduino is using a HC-06 Bluetooth module. The Arduino is supposed to receive this data and act accordingly.

However the Arduino seems to be missing bytes or just be plain slow most of the time. When testing from the computers serial connection it all works fine.

What's my issue?


texts:
I bought one of these:

There are 3 pins on it:

5V
GND
OUT

My guess is that OUT is an analogue signal that I can measure with my Arduino, am I right?

I am using the "Analogue Output" example code but I just get 5V all the time, it does not seems to change with the sound levels.

Am I doing something wrong? What am I adjusting with the blue square on the board? Should I maybe do that?


texts:
I am currently working on a project which requires me to record IR signals. (I realize there is a library available for doing this but I want to learn how to do this myself).

I tried using a simple sketch which prints out pulseIn() times on the Arduino, but then if I try to record them into an array, the Arduino misses the pulses happening while it is writing the timings to the array.

How can I achieve being able to record these fast pulses to the Arduino's memory without skipping some of the pulses?


texts:
I use a 2.8" TFT Touch Shield v1 and I want to read some data that were stred in sd and plot them with the tft.

When the following code is ordered, to access the data. TFT freezes.... but the code's execution is continued...

    pinMode(SS, OUTPUT);
    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
       Serial.println("Card failed, or not present");
    // don't do anything more:
       while (1) ;
    }

    Tempfile = SD.open("DATALOG.TXT",FILE_READ);
    if (! Tempfile) {
       Serial.println("error opening datalog.txt");
    // Wait forever since we cant write data
       while (1) ;}

I tested the code on the example of the tft graphics test... and the result was a freezed tft...

I tried also to run the example: tftbmp but the tft remains black. Once again the code is executed in the loop as i receive results from the Serial monitor but tft is black...

I use an Arduino Uno R3.

Any tip is welcomed


texts:
I am having difficulties programming what should be a simple sketch that gets my stepper motor to run at one step per second indefinitely at the press of a button and then stops at the press of another button. I am using the Bounce2.h and accelstepper.h libraries and have been unable to figure out how to do it. Any help would be greatly appreciated, and as for hardware I am using a NEMA 23 High Torque Stepper Motor connected through a M542T Motor Driver powered by a Switching Power Supply and running on an Arduino UNO.

Attatched find my code, and thank you so much for the help!

#include <Bounce2.h>
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <AccelStepper.h>

AccelStepper stepper(1, 9, 8); // initiate stepper motor

//int buttonPresses = 0;
const byte ButtonPin = 10;
const byte LedPin = 13; // for debugging and visualization

Bounce button;

void setup() {
  Serial.begin(9600);
  button.attach(ButtonPin);
  pinMode(LedPin, OUTPUT);
  stepper.setSpeed(1);
}

void loop() {
  if (button.rose()) {
    stepper.runSpeed();
    digitalWrite(LedPin, HIGH);
    //    buttonPresses++; // count presses of button and print to monitor
    //    Serial.print("Number of Button ");
    //    Serial.print("Presses = ");
    //    Serial.println(buttonPresses);
  }
  else {
    button.update();
    digitalWrite(LedPin, LOW);
    if (button.fell()) {
      stepper.stop();
    }
  }
}

As of now, a button press runs the motor at 1 step/second, but a second press or any subsequent presses thereafter do nothing to stop the motor. Thanks so much!

!!EDIT!!

Upon adding a boolean buttonState and setting it to LOW in the setup and changing my void loop() code to look like:

void loop() {
  button.update();
  if (button.rose() == true && buttonState == LOW) {
    stepper.runSpeed();
    digitalWrite(LedPin, HIGH);
    buttonState = HIGH;
  }
  else {
    if (button.fell() == true && buttonState == HIGH) {
      stepper.stop();
      buttonState = LOW;
    }
  }
}

I know get a step every button press. Just thought it may help in answering.

EDIT 2

So I I tried pulling the runSpeed() out of the loop and adding                                                            if (buttonState = HIGH){stepper.runSpeed();}
but that now just runs the stepperMotor constantly and at variable speed and will not turn it off?

EDIT 3 and Working Code
Thank you Janw for the help. I realized my fault in calling the runSpeed function within the if statement. Further, I also needed to change button.fell() to button.rose() since button.fell() returns true when the button is released, so basically I was stopping the motor everytime I let go of the button. Here is the final, and working void loop() in case anyone runs into a similar problem in the future:

void loop() {
  button.update();
  if (button.rose() == true && buttonState == LOW) {
    digitalWrite(LedPin, HIGH);
    buttonState = HIGH;
  }
  else {
    if (button.rose() == true && buttonState == HIGH) {
      stepper.stop();
      buttonState = LOW;
    }
  }
  if (buttonState == HIGH) {
    stepper.setSpeed(1);
    stepper.runSpeed();
  }
}


texts: Arduino ethernet need help with game logic!

texts:
I'm making a game where there are three LEDs and three buttons: 1 LED for 1 button. One has to press the button that has its LED lit. If it is correct, another (random) LED will light up and the game continues. However, if one presses one that isn't lit, one has points taken from one's score.

Example image: http://i.imgur.com/xSUrVRV.png

I'm having trouble figuring out how to find out when the wrong one is pressed. With the code below it will print "Ouch" whenever the led switches numbers.

Code that switches LED:

led = random(1, 4);
switch(led) {
  case 1:
    ledLeftState = HIGH;
    break;
  case 2:
    ledMiddleState = HIGH;
    break;
  case 3:
    ledRightState = HIGH;
    break;
}

Code that checks if the wrong button is pressed:

 if(digitalRead(BUTTON_LEFT) == LOW && led != 1 || digitalRead(BUTTON_MIDDLE) == LOW && led != 2 || digitalRead(BUTTON_RIGHT) == LOW  && led != 3) {
    static unsigned long lastTime = 0;
    if(millis() - lastTime > 400) {
      Serial.println("Ouch, minus ten miliseconds!");
      hurt += 10;
      lastTime = millis();
    }
  }

Hopefully you can figure this scenario out in your heads, otherwise simply tell me that you'd like code instead of downvoting.

Thanks for your time!


texts:
I'm new to Arduino and need some clarification on motor drivers.

I was wondering if I can use a L298N instead of the Motor Shield R3, I hope not to be comapring apples to oranges, the doc of the Motor Shield R3 say "The Arduino Motor Shield is based on the L298"  and more or less I see similar projects (Robot cars) using both but as mention I don't if I can use one or the other as "replacement".

(L298N)

(Motor Shield R3):


texts: Arduino auto power of circuit possible issue with higher voltage agains output pin?

texts:
I've use the following circuit to be able to shutting the my Arduino down after some time of it not being used:

I'm now concerned that while you press the button to turn on the Arduino, the 9V from the battery can flow directly to the PIN X (one of the digital pins of the Arduino configured as output). After the Arduino is started the PIN X will be set to high, to keep the Arduino running when the button is released.

Is this a problem which I need to solve? And if yes how. The finished project is intended for a child, so I assume that the on button can be hold for a long time just as it is funny to press on the button. The circuit itself is running fine.

As a possible solution I thought to add a diode between the junction after the R1 and the PIN X. Would this be an ok solution?

The circuit is not my own invention I've found it here: http://educ8s.tv/auto-power-off-arduino-simple-circuit/


texts:
I have a USB mouse which I am using to measure distance travelled by my bot for a project. I followed this blog to get the optical sensor from the mouse from the arduino and interface it with the arduino. In that blog, the USB wire has been removed and the 4 pins (VCC,GND and 2 data) are connected to the arduino

However,I found the code to not be very robust as the mouse doesn't always establish Serial communication with the arduino.

I have a USB host shield for the arduino. Is there any library which will let me get the x and y coordinates of the mouse using the USB protocol?

And if not, then is there a more stable library which will be more robust than the one used in thr blog linked above?


texts: How can I read servo motor readings via serial communication?

texts:
I'm new to serial communication. I tried to make Arduino talk to MATLAB, but certain values are allowed to be received like 100 and 101. I tried other values but didn't work. The problem is with ASCII code but I tried to subtract what is read by 48 but failed.

This is the Arduino code that I found on Google and edited it for my servo motor problem:

#include <Servo.h>
const int servoPin = 3;
int recValue; // received value from MATLAB
Servo Servo1;

void setup()
{
  Serial.begin(9600);
  Servo1.attach(servoPin);
}

void loop()
{
  if (Serial.available() > 0)
  {
    recValue = Serial.read();
    if  (recValue == 100)
    {
      Servo1.write(0);
      delay(1000);
    }
    if (recValue == 101)
    {
      Servo1.write(90);
      delay(1000);
    }
  }
}

So how can I read the correct angles that I received from the MATLAB via serial communication? Thanks.


texts: Arduino /dev/ttyUSB0 permission denied even when user added to group "dialout' on Ubuntu 18.04

texts:
I bought Arduino Mega board (CH341 usb) and I am able to connect to /dev/ttyUSB0 (upload to device) only by using sudo.

OS: Ubuntu 18.04

What I've tried:

I have downloaded Arduino IDE and added my user to dialout group. Logged out and logged in. Still nothing.
Installed Arduino by using apt
Installed Arduino by using snap

For all three cases it worked only by running as root (sudo actually). I saw couple of answers for Ubuntu 14.04 but none of answers didn't help.

I guess some other device access permissions are missing but I still didn't find any solution.


texts: How to know my Arduino core version and its location on my Ubuntu laptop?

texts:
Bakground:

When compiling a demo project about e-paper, I got this problem

./GxEPD/src/GxIO/GxIO_SPI/GxIO_SPI.h:39:5: error: ‘SPISettings’ does not name a type
     SPISettings _spi_settings;
     ^

which on the Internet, people often say your Arduino core is not up-to-date and the one installed from

sudo apt install arduino-core

is ancient. And you have to install the latest version.

Regardless of whether this solves my original problem or not, I want to have the latest Arduino core on my  laptop.
From arduino.cc I grabbed a zipped file and ran ./install.sh which did not provide enough results to know what it exactly did. Now, I am concerned that I have multiple installation in several places.

Main question:

When I run my make file and it is processed by arduino-mk, which version of arduino-core is it referred to and where is it located?

I am looking for a full proof method. I do not want to open somewhere from / directory accidentally. Because maybe this is not the arduino-core in use.


texts: How to make an arduino webserver over USB? without ethernet shield nor wifi chip

texts:
I would like to begin to understand ethernet handshakes by integrating an Ethernet over USB protocol within an arduino mega or nano. Is there something about the ethernet protocol that requires more  components? I know that USB to ethernet adapters exist. In this scenario, it would be more like a USB to arduino webserver experiment, except the arduino webserver would also be providing the IP address to the laptop during the initial handshake.
Shouldnt it be possible to create a simple router from an ATMega2560, where you plug in an arduino to a computer, and the computer is assigned an IP address on the ATMega's network?
Likewise, couldnt you then serve small files from the ATMega to a web browser through this IP connection?
I know this sounds dumb and like over engineering. But i promise i am not crazy and that this could be useful. USB to Ethernet adapters and drivers exist, so i am not sure that there is a hardware limitation. In other words, while ethernet normally requires 4 data lines and USB 2.0 has only 2 data lines, there are still kernel drivers that allow USB to work fine in this way. Likewise the ATMega has only 2 available data lines. So couldnt you begin by simulating a USB to Ethernet device firmware using the ATMega?
A new avenue here that isnt available with Serial connections would be that you could access the ATMega from a web browser, whereas in other driver modes the browser doesnt have the permission to communicate with the Mega.
Why or why not? / How could this be done?


texts: What are these components in Arduino Mega Schematic?

texts: I was looking at Arduino Mega's reference schematic here and trying to understand how the circuit functions. However, I am unable to understand what these schematic symbols (marked in black rectangles) represent or what their function is. Can anyone please explain it to me?


texts: How to avoid calling multiple times Wire.begin() in libraries?

texts:
it's all in the title ; I'm developping a library and use *TwoWire pointers in this library ; but I am using an external library that calls Wire.begin(). I've seen something about TWCR register in arduino but I don't know what it is exaclty.

Thanks in advance :)


texts: Stepper motor doesn't start immediately when i pressed the button

texts:
When I release my hand from the button on pin 2, the stepper motor takes at least few seconds to stop, but I want it stop immediately. here's my codes:

 #include <Stepper.h>

    const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
    // for your motor

    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    bool dir = false;
    bool power = true;

    void dir_pin() {
      if (!digitalRead(3)) {
        dir = !dir;
      }
    }//when the switch is being pressed
    //it condition would be different from last time

    void setup() {
      // set the speed at 60 rpm:
      myStepper.setSpeed(60);
      // initialize the serial port:
      Serial.begin(9600);
      pinMode(2, INPUT_PULLUP);//it is a easier way to using INPUT-PULLUP
      //cause you dont have to use a real resistor
      pinMode(3, INPUT_PULLUP);//why choose those two pins
      //cause for uno, the interrupt pin are pin 2 and pin 3
      attachInterrupt(digitalPinToInterrupt(3), dir_pin, FALLING);
      pinMode(A0, INPUT);
    }

    void loop() {
      int pwr = analogRead(A0) / 100;
      Serial.print("power:");
      Serial.print(power);
      Serial.print("  pwr:");
      Serial.print(pwr);
      Serial.print("  dir:");
      Serial.println(dir);
      while (digitalRead(2) == 0)
      {
        if (pwr) {
          myStepper.setSpeed(pwr);
          int pwr = analogRead(A0) / 100;

          if (dir) {
            //Serial.println("clockwise");
            myStepper.step(stepsPerRevolution);
            //delay(500);
          }
          // step one revolution in the other direction:
          else if (!dir) {
            //Serial.println("counterclockwise");
            myStepper.step(-stepsPerRevolution);
            //delay(500);
          }
        }
        else
        {
          myStepper.step(0);
        }
      }
      while (digitalRead(2) == 1)
      {
        pwr = 0;
        myStepper.step(0);
      }
      delay(10);
    }


texts:
I have accidentally released the magic smoke from the regulator on a digispark board. I did this when I accidentally plugged a circuit into the 5V and the VIn instead of the 5V and Gnd, and then plugged the board into the USB port.

The attiny chip still works - I know because I plugged it in to the USB ,with no circuitry attached, and the uploaded program still runs happily.

My question is, is there any possibility that when the magic smoke was released from the regulator, the attiny was also damaged?

Secondly, is there any harm in leaving the dead regulator on the board? Or am I better off cutting it off?


texts: Arduino Yun not showing anything on the serial monitor

texts:
I am having issues with the ArduinoYun. It's not showing any data in the serial monitor. The sensor lights up when I plug it in but that's about it and the code seems to compile but nothing is coming through. I am using the Adafruit color sensor. I have SDA/SCL connected to pins 4 and 5. The servo is connected to pin 3. The rest is just on Vin and GND.

#include "Servo.h"
#include "Wire.h"
#include "Adafruit_TCS34725.h"

const int redPos = 160;
const int orangePos = 130;
const int yellowPos = 100;
const int greenPos = 70;
const int bluePos = 30;
const int nonePos = 0; // Kein Objekt erkannt

Servo myservo;

Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_1X);

void setup() {
  Serial.begin(9600);
  Serial.println("Makerblog.at - MuMs Color Sensor");
  if (tcs.begin()) {
    Serial.println("Sensor gefunden");
  } else {
    Serial.println("TCS34725 nicht gefunden ... Ablauf gestoppt!");
  while (1);
  }
  // Der Servo hängt am PWM-Pin 3
  myservo.attach(3);
  // Servo in Grundstellung fahren
  myservo.write(0);
  delay(1000);
}

void loop() {
  uint16_t clearcol, red, green, blue;
  float average, r, g, b;
  delay(100); // Farbmessung dauert c. 50ms
  tcs.getRawData(&red, &green, &blue, &clearcol);
  average = (red+green+blue)/3;
  r = red/average;
  g = green/average;
  b = blue/average;

  // Clear-Wert und r,g,b seriell ausgeben zur Kontrolle
  // r,g und b sollten sich ca. zwischen 0,5 und 1,5
  // bewegen. Sieht der Sensor rot, dann sollte r deutlich über 1.0
  // liegen, g und b zwischen 0.5 und 1.0 usw.
  Serial.print("\tClear:"); Serial.print(clearcol);
  Serial.print("\tRed:"); Serial.print(r);
  Serial.print("\tGreen:"); Serial.print(g);
  Serial.print("\tBlue:"); Serial.print(b);

  if ((r > 1.4) && (g < 0.9) && (b < 0.9)) {
    Serial.print("\tROT");
    myservo.write(redPos);
  } else if ((r < 0.95) && (g > 1.4) && (b < 0.9)) {
    Serial.print("\tGRUEN");
    myservo.write(greenPos);
  } else if ((r < 0.8) && (g < 1.2) && (b > 1.2)) {
    Serial.print("\tBLAU");
    myservo.write(bluePos);
  } else if ((r > 1.15) && (g > 1.15) && (b < 0.7)) {
    Serial.print("\tGELB");
    myservo.write(yellowPos);
  } else if ((r > 1.4) && (g < 1.0) && (b < 0.7)) {
    Serial.print("\tORANGE");
    myservo.write(orangePos);
  } else {
    Serial.print("\tNICHT ERKANNT");
    myservo.write(nonePos);
  }
  Serial.println("");
  delay(100);


texts:
I have a ds3231 and Arduino UNO and I need to get an interrupt from ds3231 once a week for example every Fridays. I've searched a lot in the internet and forums but did not find any library or code that have weekly alarm or some of them that had, they didn't work well.
I also read the data sheet of ds3231 but didn't understand how to set the registers of it.
can anyone help?


texts: Issue with removing files progrmatically created under "/www/..."

texts:
I am having an issue with removing temporarily files I am creating under the /www directory. I have a subdir, "/www/csv",  where csv formatted files are being written based on sensor data. The files are created on-demand on the YUN, placed in the /www/csv dir, with the whole process driven by a REST call and an AJAX implementation in a browser.  The files are created with no problem with a Filesystem.open(path, FILE_WRITE); call. I can also use the Process calls from the bridge library to rename the file after it is full written. However, if I try to use Process calls (i.e. p.begin("rm");, etc, etc) to remove the files after use, the files are never deleted. I also tried the "mv" the files to /tmp so they would get cleaned up by the OS eventually, but that fails also. I have the rights to /www and /www/csv set to "777". I am assuming this is an access rights issue, however I am unsure what user my REST calls are running as (it would be whatever the default is for a YUN as I have created no additional users on the system).

Thanks in advance,
Pete


texts:
So I wanted to make a rc car based on two arduino nanos, two nrf24l01 (rx and tx), and a pololu brushed motor driver (this one) and it worked, more or less. Sometimes it worked very well and everything went nice and suddenly "freezes" and stops receiving and when it does always the servo goes to 0°(I think it must be the Rx because it prints the same value till he next restart in the serial monitor).
It seems the servo trebles in the same direction (to 0°) only when I send high pwm values until stops reading new data and "freezes".
I have 2 batteries, one for the nano with a step up converter and other for the servo and the brushed motor and they share a common ground.  Everything is close to each other and connected by wires soldered to a prototype breadboard. It is really messy but makes a good contact.
So it seems like a noise problem, isn't it? But what else it could be? How can I suppress that noise? I have already watched the pololu guide about noise but I didn't try the bypass capacitors since I don't know how to solder them propperly (can they burn the servo?)
Here is the code for the Tx

#include <SPI.h>
#include "RF24.h"
const int ledBot = 8;
const int padx = A0;
const int pady = A1;
const int sw = 3;
int sws;
int x;
int y;
int botState;
int aBotState;
int ledState;
const float un = 0.25;
const float fy = 0.176;
int sens [4]; // 0: throttle, 1: foward/backwards, 2: steering, 3: lights

RF24 radio(9, 10); // CE, CSN
const byte address[6] = "00001";
void setup() {
  //Serial.begin(9600);
  pinMode(padx, INPUT);
  pinMode(pady, INPUT);
  pinMode(sw, INPUT);
  pinMode(ledBot, INPUT_PULLUP);
  radio.begin();
  radio.setDataRate (RF24_2MBPS);
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();

}
void loop() {
  x = analogRead(padx);
  y = analogRead(pady);
  sws = digitalRead(sw);
  botState = digitalRead(ledBot);
  y = 1024-y;

  switch (sws){ //foward and backwards

  case 0:
    sens [0] = un*x;
    sens [1] = 0;
    sens [2] = min(135, max(50, y*fy-2));
    break;

  case 1:

    sens [0] = un*x;
    sens [1] = 1;
    sens [2] = min(135, max(50, y*fy-2));
    break;
  }

  if ( botState == HIGH && aBotState == LOW){ //button switch part
    if (ledState == 0){
      ledState = 1;
      sens [3] = ledState;
    }
    else {
      ledState = 0;
      sens [3] = ledState;
    }
  }
  aBotState = botState;
  radio.write(&sens, sizeof(sens));

  //Serial.println(sens[0]);
 //Serial.println(ledState);
 // Serial.println(sens[1]);
 //Serial.println(sens [3]);

}

And here for the Rx
#include <Servo.h>
#include <SPI.h>
#include "RF24.h"

int sens [4];
const int polph = 7;
const int polen = 6;
const int led1 = 2;
const int led2 = 3;
const int ledError = 8;

Servo servo;
RF24 radio(9, 10); //
const byte address[6] = "00001";

void setup() {

  pinMode(polph, OUTPUT);
  pinMode(polen, OUTPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);

  pinMode(ledError, OUTPUT);
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
  delay(300);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  delay(300);
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
  delay(300);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  servo.attach(5);
 //Serial.begin(9600);
  radio.begin();
  radio.setDataRate (RF24_2MBPS);
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();

}
void loop() {
  if (radio.available()) {
    digitalWrite(ledError, LOW);
    radio.read(&sens, sizeof(sens));
    analogWrite(polen, sens [0]);
    digitalWrite(polph, sens[1]);
    servo.write(sens [2]);
    digitalWrite(led1, sens [3]);
    digitalWrite(led2, sens [3]);

  }

}

Thanks for replying.


texts: Serial communication PC to Arduino using C and send via NRF

texts:
I'm trying to communicate my PC with an Arduino Mega via serial and after send the message via NRF to another Arduino.

But I don't know if the message is send correctly or if it even send the message. Because I can't debug using Serial Monitor. If it is opened the serial port appear as busy.

When I execute the code the TX led on the Arduino blinks, but nothing is send via NRF.

I made some tests using only the NRF between the Arduinos and it's working, but when I try using the PC - Arduino serial communication, nothing happens.

C Code

#include <stdio.h>
#include <string.h>

char arduinoPort[] = "/dev/ttyACM0";

int main() {

  char buffer[] = {'1'};
  int error = 10;
  FILE *usb_port;

  usb_port = fopen(arduinoPort, "rwb");

  if(!usb_port) {
    perror(arduinoPort);
    return 1;
  }

  //memcpy(buffer, &error, sizeof(error));
  fwrite(buffer, sizeof(char), sizeof(buffer), usb_port);

  fclose(usb_port);

  return 0;
}

Arduino Code

#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

RF24 radio(7, 8); // CE, CSN

uint64_t address = 0xF0F0F0F0E1LL;

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

  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
  radio.printDetails();

}

void loop() {

  if(Serial.available() > 0) {

    char byteLido = Serial.read();

    radio.write(&byteLido, sizeof(byteLido));
    delay(1000);
  }
}


texts: PWM voltage appears to be low (~0.33V) and fails to trigger a PWM dimmer LED controller

texts:
I am attempting to use the Arduino Uno to tune the current on a SparkFun Femtobuck LED driver. The driver itself appears to work fine and outputs 0.33A when the PWM pins are not connected.

However, when I used a simple program to tune the current up and down with PWM, the driver outputs a constant 0.26A instead of the expected ramping current.

I don't have an oscilloscope, so I attempted to measure the voltage with a multimeter. I observe the voltage ramp from 0 to 0.33V across the output (digital pin 9) and the ground pins. This ramping also corresponds to the blink pattern of the builtin LED pin in the program.

When I manually set the PWM to 255, I also measure a voltage of 0.33V across the output and ground pins. I expected the PWM voltage to be 5 volts since that is the Vcc of the PWM pins.

The only hit I could find after some research was this one https://forum.arduino.cc/index.php?topic=280890.0 , which was due to an incorrect measurement multiplier being used. I have measured the input voltage across the Vin and GND power pins (12V 2A wall plug) and I obtained 11.6V, which is in the expected range. The PWM output voltages are the same when I power the Arduino with a USB cable instead of the wall plug.

The program is attached below:

int ledPin = 9;    // PWM signal to digital pin 9

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(ledPin, OUTPUT);  // sets the pin as output
}

// the loop function runs over and over again forever
void loop() {
  // fade in from min to max in increments of 5 points:
  for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
    // sets the value (range from 0 to 255):
    analogWrite(ledPin, fadeValue);
    //Use the ms value to simulate the fade on the LED.
    digitalWrite(LED_BUILTIN, HIGH);
    delay(fadeValue/2);
    digitalWrite(LED_BUILTIN, LOW);
    delay(128-fadeValue/2);
  }

  // fade out from max to min in increments of 5 points:
  for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
    // sets the value (range from 0 to 255):
    analogWrite(ledPin, fadeValue);
    //Use the ms value to simulate the fade on the LED.
    digitalWrite(LED_BUILTIN, HIGH);
    delay(fadeValue/2);
    digitalWrite(LED_BUILTIN, LOW);
    delay(128-fadeValue/2);
  }
}

Based on the comments, I have also attached the program used to fix the PWM at 100% duty cycle:

int ledPin = 9;    // PWM signal to digital pin 9

// the setup function runs once when you press reset or power the board
void setup() {
  pinMode(ledPin, OUTPUT);  // sets the pin as output
}

// the loop function runs over and over again forever
void loop() {
  analogWrite(ledPin, 255);
  delay(1000);
}


texts:
I have an Arduino Uno whose LED, which is connected to  pin 13, is not turning off and it always stays on, and it annoys me.

Touching any exposed pins turns off the LED after removing my hands from the pins it turns back on slowly.

However it works perfectly with the programs. This program does turn the LED off and it stays that way while the program is running.

void loop() {
  digitalWrite(13, LOW);
}

When I upload other programs that don't use pin 13 then it stays on again. How can I fix this?


texts: Arduino Nano no serial port for MacBook Air 2013

texts:
Problem

I have an Arduino Nano connected via a USB cable (Type A to Mini Type B) to my MacBook Air (Mid 2013 Model). The PWR LED is on while the arduino is connected.

Opening the Arduino software, pulling down the Tools > Serial Port menu does not show me a valid serial port. All I see is:

/dev/tty.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/cu.Bluetooth-Modem

What I've tried and did not work

I have installed the correct FTDI driver (v2.2.18). x64 for my MacBook Air's Corei5, file FTDIUSBSerialDriver_10_4_10_5_10_6_10_7.mpkg. Restarted after installation.
Tried connecting arduino to both USB ports on my Air.

More Info

Running Mac OSX 10.10 Yosemite
Same arduino and cable work when connected to a Windows machine or a Raspberry Pi.

If it helps, I can see the USB Serial in my Apple Logo > About This Mac > System Report under Hardware > USB

USB2.0-Serial:

  Product ID:               0x7523
  Vendor ID:                0x1a86
  Version:                  2.54
  Speed:                    Up to 12 Mb/sec
  Location ID:              0x14100000 / 8
  Current Available (mA):   500
  Current Required (mA):    Unknown (Device has not been configured)

I'm out of ideas and options. Any help would be greatly appreciated.

Thanks in advance :)


texts:
My problem is simple yet extremely problematic. For some reason, I cannot interact with an SD card and a LED strip at the same time with my arduino. After hours of testing multiple scripts, I am 99.99% that the issue is due to the SPI.h library.
I have tried the simplest LED strip code, such as turning on led number 5. If I include SPI.h, the code does not work, the data LED of the arduino doesn't even light up, the arduino doesn't send anything to the strip data line. If I remove include SPI.h, the code works.
This is really odd, I have read about the SPI.h messing with the pins, so now I'm looking for a solution, to use the SD card module without the SPI library if it is possible.
Here is an example of a code that does not work due to the use of the SPI.h library.

Any help is greatly appreciated, this is extremely odd and problematic.

#include <Time.h>
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#include <SPI.h>
#include <SD.h>

Sd2Card card;
SdVolume volume;
SdFile root;

const int chipSelect = 4;

#define PIN            6
#define NUMPIXELS      400

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB +   NEO_KHZ800);

boolean stringComplete = false;  // whether the string is complete
boolean readarray=false;
String inString = "";
int c=0;
int cc=0;
int led=0;
int i=0;
int j=0;
int pixel_n=0;
unsigned long start;
unsigned long endd;

//char* ledd[]={"", "", ""};
int ledd[3]={0,0,0};

File myFile;

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

Serial.print("\nInitializing SD card...");

// Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
if (!volume.init(card)) {
  Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
  return;
}

// print the type and size of the first FAT-type volume
uint32_t volumesize;
Serial.print("\nVolume type is FAT");
Serial.println(volume.fatType(), DEC);
Serial.println();

Serial.println("Ok we're done");
delay(2000);

pixels.setPixelColor(5, (200,200,200)); // THIS DOES NOT WORK
pixels.show(); // THIS EITHER

  Serial.begin(9600);
}

void loop(void) {

}


texts: Arduino not recognised by windows after using a lot of the storage

texts: I made a script for my Arduino Pro Micro that was very large (Global variables were 98% of the intended storage). The Arduino was not recognised by Windows after loading the script and I don't know how to fix this issue.


texts:
I want to detect wether a display is connected or not.
This is the display: https://www.az-delivery.de/en/products/1-77-zoll-spi-tft-display
I read connecting a pin of the display with another pin with a pull up resistors. Unfortunetely nothing worked so far.
My microcontroller board is Arduino Mega.


texts: How to HTTP post a data to Node express API from a Arduino esp8226?

texts:
I am HTTP posting a data to this web API https://morning-cliffs-85779.herokuapp.com/api/users from an Arduino connected to esp8226. I am using the wifiesp library to HTTP_POST data.

The REST APIs are hosted in Heroku.

When I post it the Arduino gives the response

  Connected to server
  [WiFiEsp] Data packet send error (2)
  [WiFiEsp] Failed to write to socket 3
  [WiFiEsp] Disconnecting  3

and the Heroku server gives the response

  at=error code=H13 desc="Connection closed without response"

Below is the Arduino code:

  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    String content = "id=5bc58842bdfea0153bb27214&volt=7";
    client.println("POST /api/users HTTP/1.1");
    client.println("Host: morning-cliffs-85779.herokuapp.com:80");// ("Host": host:port)
    client.println("Accept: */*");
    client.println("Content-Length: " + content.length());
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println();
    client.println(content);
  }

This is the Node Express API:

app.post('/api/users', function (req, res) {

console.log('here');

if (req.body.id) {
    DevReading.findByIdAndUpdate(req.body.id, {
        volt: req.body.volt
    }, function (err, reading) {
        if (err) throw err;

        res.send('Update Success');
    });
}

else {

var newDevReading = DevReading ({
    deviceName: 'test',
    volt: req.body.volt
});

newDevReading.save(function (err) {
    if (err) throw err;
    res.send('Reading Post Success');
});
}

});


texts: Unable to get Arduino Ethernet Shield IP address connected to Raspberry

texts:
My Arduino Uno with Ethernet Shield is connected to a Raspberry (rasp1) and the Ethernet Shield is connected to another Raspberry (rasp2) by Ethernet cable; rasp2 has a private IP address (192.168.10.0). I want to find out the Arduino IP address.

I used the example sketch  DHCPAddressPrinter but when running it the Serial Monitor remains empty (as Mac Address I used the address located underneath the shield).

Code Used:

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
    0x90, 0xA2, 0xDA, 0x11, 0x32, 0x49
};

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    // this check is only needed on the Leonardo:
    while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
    }

    // start the Ethernet connection:
    if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        for (;;)
        ;
    }
    // print your local IP address:
    Serial.print("My IP address: ");
    for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(Ethernet.localIP()[thisByte], DEC);
        Serial.print(".");
    }
    Serial.println();
}

void loop() {


texts:
I try move my projects from atmega to ESP8266-07 modules. I connect ESP8266-07 to FT232:

(ESP) RX -------- TX (FT232)
(ESP) TX -------- RX (FT232)
(ESP) GND ------- GND (FT232)
(ESP) VCC ------- VCC 3.3V (FT232)
(ESP) EN -------- VCC 3.3V (FT232)
(ESP) GPIO0 ----- GND (FT232)
(ESP) GPIO15 ---- GND (FT232)

I can upload sketch and it's work. BUT...

... WHEN I restart ESP (software reset or hardware reset - unplug power) program no starting. I try change connections after upload like:

Try 1:
(ESP) RX -------- TX (FT232)
(ESP) TX -------- RX (FT232)
(ESP) GND ------- GND (FT232)
(ESP) VCC ------- VCC 3.3V (FT232)
(ESP) EN -------- VCC 3.3V (FT232)

Try 2:
(ESP) RX -------- TX (FT232)
(ESP) TX -------- RX (FT232)
(ESP) GND ------- GND (FT232)
(ESP) VCC ------- VCC 3.3V (FT232)
(ESP) EN -------- VCC 3.3V (FT232)
(ESP) GPIO0 ----- VCC 3.3V (FT232)

Try 3:
(ESP) RX -------- TX (FT232)
(ESP) TX -------- RX (FT232)
(ESP) GND ------- GND (FT232)
(ESP) VCC ------- VCC 3.3V (FT232)
(ESP) GPIO0 ----- VCC 3.3V (FT232)

But everytime sketch does not start after upload. This is not a code problem, because I try start "blink" sketch or other. Everytime ESP work once, after upload.


texts: Arduino as analog to digital converter for temperature sensor

texts:
I have an ESP8266 module that must receive some data and send it to a server, my problem is that this data is given by a temperature sensore and a light sensor which must be connected to analog pins and my ESP has only 2 digital pins.

So I thought that I can measure the temperature and the light with an arduino (the sensors are the ones included in arduino starter pack) and then connect my esp digital pins to arduino digital pins and write a sketch to send digital data as output of arduino.

I think this is possible but I can't figure out how to do it because I can only set pins to high or low.

Can somebody help me? Thanks a lot

P.S: I already tried ther solutions like connecting tx and rx of esp to arduino but they didn't work so I prefer to use ESP8266 as standalone


texts:
I am using the following setup on my Arduino UNO to measure cpu fan RPMs:

The code is set to bring the trigger pin for each transistor high when it is checking that fan's RPM and FreqMeasure.h is then used to check the frequency of the signal on pin 8 which is then translated to RPM and sent to the LCD display.

I am experiencing reading issues and suspect that the signal is remaining on the measuring bus during the subsequent reads, however before revamping my code I simply wonder:

Is my circuit logic sturdy? I am just getting my feet back under me with microprocessors and have always found transistors to be a tricky subject, thanks in advance for your help!

If you'd like to see more info all can be found on GitHub.


texts: What should be expected if the code in the timer interrupt ISR does not finish before the interrupt is called again?  For example Timer0 ISR(TIMER0_COMPA_vect){} on the Uno.  This is for debugging purposes in a complex program.  Thanks.


texts:
I am using an RC522 reader with Arduino UNO.  This is the library I am using.
But, when I try a firmware check, in the serial I get this error: Firmware version: 0x12,  result: defect or unknown
I checked the connections and they were all correct.  My RC522 needs 3.3v and it is connected to the 3.3v pin of my Arduino board. Also, all the pins are soldered.
Here is the code of the firmware check (it came with the library):
/*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program to test your firmware.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 *
 * This example test the firmware of your MFRC522 reader module, only known version can be checked. If the test passed
 * it do not mean that your module is faultless! Some modules have bad or broken antennas or the PICC is broken.
 *
 * @author Rotzbua
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

/**
 * Check firmware only once at startup
 */
void setup() {
  Serial.begin(9600);   // Initialize serial communications with the PC
  while (!Serial);      // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin();          // Init SPI bus
  mfrc522.PCD_Init();   // Init MFRC522 module
  delay(5);

  Serial.println(F("*****************************"));
  Serial.println(F("MFRC522 Digital self test"));
  Serial.println(F("*****************************"));
  mfrc522.PCD_DumpVersionToSerial();  // Show version of PCD - MFRC522 Card Reader
  Serial.println(F("-----------------------------"));
  Serial.println(F("Only known versions supported"));
  Serial.println(F("-----------------------------"));
  Serial.println(F("Performing test..."));
  bool result = mfrc522.PCD_PerformSelfTest(); // perform the test
  Serial.println(F("-----------------------------"));
  Serial.print(F("Result: "));
  if (result)
    Serial.println(F("OK"));
  else
    Serial.println(F("DEFECT or UNKNOWN"));
  Serial.println();
}

void loop() {}

Edit: The process i followed to install the the library was: Sketch > include library > add .Zip library


texts: Arduino connection websocket always fails

texts:
I am using the Arduino Websocket Client library to connect my Arduino Uno to a Socket.IO server. But the connection always returns 0 (fail) after the handshake.
Anyone has used this library before? How could I debug this?

#include "Arduino.h"
#include <Ethernet.h>
#include <SPI.h>
#include <WebSocketClient.h>

byte mac[] = {0xB8,0x27,0xEB,0x7E,0x2D,0xC9};
char server[] = "labathome.rexlab.ufsc.br";
int port = 8001;
WebSocketClient client;

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac);
  Serial.println(client.connect(server, port));
  client.setDataArrivedDelegate(dataArrived);
  client.send("Hello World!");
}

void loop() {
  client.monitor();
}

void dataArrived(WebSocketClient client, String data) {
  Serial.println("Data Arrived: " + data);
}

PS: I tested the server and it works fine, and I also tested with a normal WS server instead of the Socket.IO, and nothing :(


texts: Trying to turn off fading RGB LED after 30 secs

texts:
I am trying to get something to work so that an RGB LED fades through the color spectrum, and when a button is pressed some music plays.
That is not the problem.
Assume I am using any loop that functions can be called at any time in.
I am trying to make it so that if the button is not pressed for a certain amount of time, say 30 seconds, the light stops fading through the color spectrum and when the button is pressed in this 'sleep mode', first the light starts fading, and then the next press plays the music.
I am aware this could be done somehow with millis();, but how would I approach this?
I am using an Arduino Uno.


texts: PS4 controller too touchy on the arduino RC car i built

texts:
I recently built an RC car from scratch and I am using a PS4 controller to control it.  I have an ESC of course but my problem is I barely touch the joystick and the motor is going so fast I cannot control the car. Here is the code and any help would be much appreciated.

/*
 Example sketch for the PS4 Bluetooth library - developed by Kristian Lauszus
 For more information visit my blog: http://blog.tkjelectronics.dk/ or
 send me an e-mail:  kristianl@tkjelectronics.com
 */

#include <PS4BT.h>
#include <usbhub.h>
#include <Servo.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
Servo servo1;  //Steering Servo
Servo servo2;  //DC Motor

/* You can create the instance of the PS4BT class in two ways */
// This will start an inquiry and then pair with the PS4 controller - you only have to do this once
// You will need to hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode
PS4BT PS4(&Btd, PAIR);

// After that you can simply create the instance like so and then press the PS button on the device
//PS4BT PS4(&Btd);

bool printAngle, printTouch;
uint8_t oldL2Value, oldR2Value;

void setup() {
  Serial.begin(115200);
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); // Halt
  }
  Serial.print(F("\r\nPS4 Bluetooth Library Started"));

  pinMode (3, OUTPUT);
  pinMode (5, OUTPUT);
  servo1.attach (3);
  servo2.attach (5);
}
void loop() {
  Usb.Task();

  if (PS4.connected()) {

    {
    servo1.write(map(PS4.getAnalogHat(RightHatX), 0, 255, 50, 0));
       //map values from the x-axis of the right analog stick
    servo2.write(map(PS4.getAnalogHat(LeftHatY), 0, 255, 0, 180));
       //map values from the y-axis of the left analog stick
    }}

    else

    {
      servo1.write (25);  // set servo motor to 0 point
      servo2.write (90);  // Turn DC motor off
    }


texts: How can I speed up reading of an SD card?

texts:
I am working on a project using an Arduino as a web server.

Code:

webFile = SD.open("index.htm");
if (webFile) {
  while(webFile.available()) {
    client.write(webFile.read());
  }
webFile.close();

This sends data line by line, leading to a long time to load the webpage. Is there a faster way to load this page?


texts: 3,6V DC motor spinning with L298N and Arduino

texts:
I'm trying to control a re used DC motor from a drill (3,6V) with a L298N and a Arduino. It's powered with a 5V - 60A power supply.

I tried to follow this step by step tutorial (https://www.youtube.com/watch?v=dyjo_ggEtVU) but the motor is not spinning..yet. I can ear a noise, it starts to spin a micron and then stops.

I though that it could be something wrong with the power supply but I connected the 4V battery from the drill and the same thing is happening. If I connect the motor directly to the battery it is spinning nicely...

I though then that it was a code issue but I tried a no load test and measured the voltage without the motor -> I've the 4V required voltage. When the motor is connected I have 300mV instead of 4V.

Do you know what could go wrong? Is the L298 dead? just got it a few hours ago...

Would be nice if you have any clue.

Many thanks.

// Commande moteur
    int enA = 9;
    int in1 = 8;
    int in2 = 7;

void setup()
{
  // Définition des sorties

  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);

  //Sens de rotation du moteur

  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);

  //Vitesse de rotation du moteur

  analogWrite(enA, 200);

  //Delay

  delay(5000);

   //Arrêt du moteur

  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
}

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

}


texts: Using Li-Poly battery to run UNO + Adafruit data logger

texts: I want to power Arduino UNO+Adafruit data logger (https://www.adafruit.com/product/1141) with a 3.7V 2000mAh Li-Poly battery. I am providing an excitation voltage of 3V, through one of the digital pins and a potential divider arrangement, to a sensor which is providing output signal in analog (voltage) form. I am using ADC to read that voltage. My question is, since the battery voltage is going to drop during its operation, would the voltage output from the digital pin, and thus the potential divider, also drop? Could this voltage drop also affect the reference for the ADC?


texts: Powering Multiple Servos From One Battery- What is my circuit missing?

texts:
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: http://imgur.com/BRrWijV


texts: Arduino + HM-10/11 + ANCS to get notifications for iPhone

texts:
I am wondering if there are any current solution to receive notifications on iPhone through ANCS and HM-10/11 Bluetooth LE module. An Arduino library?

https://stackoverflow.com/questions/28488529/is-it-possible-to-use-hm-10-or-hm-11-ble-module-with-arduino-to-communicate-with/30625967#30625967

One of the answer of this question talked about a number of AT commands that can be used to configure the HM-10/11 to use the ANCS. But the part receiving and getting the notification details seems to be quite complicated. In addition, it should also require an iOS app to establish the connection according to the note below 1.5.

There seemed to be no information online about this even though the manufacturer confirmed with me they do provide support for ANCS for this module.

Are there anyone working on this with an Arduino? Could you please share more about this?

Or are there anyone who can help develop this library together?


texts: Durable, thump resistant, buttons, at a cheap price

texts:
Not really an Arduino specific question, but I guess a lot of people on this board are also hobbyists, so they might have done something similar...

For my project I need to connect buttons to the Arduino. The Arduino itself will be in a safe area, but the buttons will be pressed by "members of the public", some of whom will get carried away with what is meant by the term "push the button". I'm confident of building a sturdy housing for the button panel (which is a separate box from the Arduino housing), but I'm wondering if anyone has a source for sturdy buttons. I know that arcade suppliers are quite durable, but has anyone got experience of a particular type/mounting technique that hit the sweet-spot between price and durability/reliability.

Industrial supplies are hard-wearing, but a bit pricey.


texts:
I have a RDM6300 RFID module which I am trying to connect to an ESP8266 by using rdm6300.h library.
I had it all up an running all along with other components but we had connected to the ESP8266 but we had to move from the breadboard to an actual wired setup. Everything kept on working except for the RFID reader. The way I used to do it was by making a reference to this approach (more or less):
#include <rdm6300.h>

#define RDM6300_RX_PIN 4
#define READ_LED_PIN 13

Rdm6300 rdm6300;

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

    pinMode(READ_LED_PIN, OUTPUT);
    digitalWrite(READ_LED_PIN, LOW);

    rdm6300.begin(RDM6300_RX_PIN);

    Serial.println("\nPlace RFID tag near the rdm6300...");
}

void loop()
{
    /* if non-zero tag_id, update() returns true- a new tag is near! */
    if (rdm6300.update())
        Serial.println(rdm6300.get_tag_id(), HEX);

    digitalWrite(READ_LED_PIN, rdm6300.is_tag_near());

    delay(10);
}

but now, after the re-arrangement it just stopped reading tags. What I did was to disconnect everything from the ESP and leave only the RDM6300 connected to it with the sample code. Unfortunately, it doesn't seem to detect any tags.
In order to test if the components are failing for some reason, I decided to test it by using SoftwareSerial.h library on it like this:
#include <SoftwareSerial.h>
SoftwareSerial RFID(2, 3); // RX and TX

int i;

void setup()
{
  RFID.begin(9600);    // start serial to RFID reader
  Serial.begin(9600);  // start serial to PC
}

void loop()
{
  if (RFID.available() > 0)
  {
     i = RFID.read();
     Serial.print(i, DEC);
     Serial.print(" ");
  }
}

and it worked perfectly fine. I was able to read the payload coming from the chip:

2 30 31 30 46 33 46 38 44 39 31 32 44 3

But, since I don't want to implement everything related to decoding this serial stream I decided to ask for your opinion what could be wrong here. It used to work without any problem but now it doesn't.
There is something interesting which I also noticed. When I run the first code snipped and change the ESP8266 pin used from 4 to 16(D0) and I upload it, once I move the tag close to the antenna the hardware light related to this pin starts flashing and when I bring the tag back (away from the antenna) it stops flashing.
This makes me thing that on a hardware level everything is fine but some software issues are happening.


texts: Cannot import library file from ESP32 sdk library in "Eclipse C++ IDE for Arduino" project

texts:
I have successfully installed "Eclipse C++ IDE for Arduino" and the Plugin works fine. Now I installed a custom board (ESP32) by adding package_index.json URL in windows>prefrences>C/C++>Arduino. The board installed and also work fine.
The only problem I'm facing is that I'm unable to import platform SDKs and libraries.(e.g. #include "driver/adc.h") which are present in the path: G:\program\eclipse.arduinocdt\packages\esp32\hardware\esp32\1.0.2\tools\sdk\include
I just want to import files just like in the Arduino IDE.

Eclispse version :
Eclipse IDE for C/C++ Developers
Version: 2019-03 (4.11.0)
Build id: 20190314-1200

Thank You


texts: Trouble using lcd.readButtons() in RGBLCDShield library

texts:
I am trying to create a state machine that loops in whatever state it's in until a button is pressed.  I am using the Adafruit_RGBLCDShield library along with the LCD shield and 16x2 display.  For some reason the buttons aren't being detected at all.  Here is the code for one of the states:

    case STANDBY_MODE:
  lcd.clear();
  lcd.setBacklight(0x0);
  delay(100);
  noInterrupts();
  digitalWrite(fire, LOW);
  digitalWrite(chg, LOW);
  digitalWrite(trig, LOW);
  analogWrite(eprgm, 0);
  // Wait for button press
  while(1)
  {
    button = lcd.readButtons();
    if(button)
    {
      showLCD();
      t0 = millis();
      state = NO_CHARGE;
      analogWrite(eprgm, (vSet*0.0204)/5);
      interrupts();
      return;
    }
  }
break;

In this state, the system turns off all outputs and display and waits for a button to be pressed.  For some reason, though, it doesn't respond when I press the button.  Is there something missing here?


texts: Digital Band pass filter arduino 1100-1300 Hz

texts:
For a project I need to design an digital band pass filter. I started of with this in Matlab:

wch=1100*2*pi;
wcl=1300*2*pi;

sys=tf([1/wch 0],[1/(wch*wcl) 1/wch+1/wcl 1])
sysd=c2d(sys,9615,'tustin')

so I got this values:

3.01e-08 z^2 - 3.01e-08/(z^2 + 2 z + 1)

Then I rewrote it to:

y[k] = 3.01*10^-8*u[k]-3.01*10^-8*u[k-2] -y[k-2]-2y[k-1]

and so I put hoped that this arduino script should do the Job:

#include <TimerOne.h>

float out;

float second_filt(float x0) {
  static float y1=0;  // y[n-1]
  static float y2=0;  // y[n-2]
  static float x1=0;  // x[n-1]
  static float x2=0;  // x[n-2]
  float y0 = 3.01*10^(-8)*x0-3.01*10^(-8)*x2-2*y1-1*y2 ;

  // Shift values
  y2 = y1;  // Shift y[n-1] to y[n-2]
  y1 = y0;  // Shift y[n] to y[n-1]
  x2 = x1;  // Shift x[n-1] to x[n-2]
  x1 = x0;  // Shift x[n] to x[n-1]
  return y0;
}

void setup() {
  Timer1.initialize(32); //Initialize timer with a period of 32 us
  Timer1.pwm(9,0); // Use pin 9 for PWM
}

void loop() {
  if (isTime()) {
    out=second_filt(analogRead(0));
    Timer1.setPwmDuty(9,out); //Sets the duty cycle to the analog value on pin 0
  }
}

bool isTime(){ //Checks if 300 us elapsed since the last call
  static unsigned long t0=0;
  static unsigned long t1=0;

  t1 = micros();

  bool res = (t1-t0)>300;

  if (res) {
    t0 = t1;
  }
  return res;
}

Now I don't know what the error: 'invalid operands of types 'double' and 'double' to binary 'operator^' means and I am not sure if this is actually gonna work. Pleas help me out I have been busy with this for days.


texts: What is the best way to init wifi communication between two devices (get IP address)?

texts:
what is the best way to init wifi communication between two devices without knowing IP of second device, let's say Raspberry Pi and ESP8266?
I want to build simple home automation system for my purpose. There will be Raspberry Pi, as heart of system and ESP8266 as controlled devices. What is best way to get them communicate? I think, the hardest think is how to get their IP address. Then it will be easy to communicate via sockets.
In next text, by RPi I mean Raspberry Pi and program in RPi will be in python (but using call of terminal commands when needed).
My idea is this: On ESP8266 will be running program, which will create WiFi Acces Point at start (on first run in network). Name (SSID) of that AP will be specific (let's say starting with ESP-AUTOMATION prefix), so Raspberry Pi will know, when new ESP device will be turned on (Raspberry Pi will repeatedly search for accesible networks). When new ESP appear, RPi will save own IP to variable and connect to newly searched network (let's say ESP-AUTOMATION-abcd). Then will RPi send to AP (ESP) it's (RPi's) IP address and local network SSID and password. Then it will disconnect, and connect back to local network (and gain it's "old" IP, which it previously saved to variable). Then ESP connect to local network with static IP and after succesfull connect, it will send to RPi it's IP address via socket (because IP addr of RPi it will already known, because RPi have send it when it served as AP). Then RPi will save that IP address. And because IP addresses (of RPi and also ESP) will be configured as static, it shouldn't change over time.
Is this good idea? Or is something of that unreal (I am at beginning of that all)?
PS: I really want completely autonomous system, so for me is not solution something like connect ESP to PC and print it's IP to serial and then it write to RPi...
Thanks for every advice/opinion.


texts: Using SMS to receive password, then to choose whether to turn the relay on or off

texts:
I'm trying to use SMS messages to turn a relay on/off but before doing that i need to have a password system before allowing the user to turn the relay on/off. Basically, you have to send the password to the GSM via SMS first, then have an option select of ON or OFF, which you also send to the GSM. I can already do the password and ON/OFF of the relay separately, but I'm having trouble trying to combine them together. Here is the code:

String _buffer;
String number = "+639562284415";
String textMessage;
String relayState = "HIGH";

int relay = 24;
int _timeout;

void setup() {
  pinMode(relay, OUTPUT);
  digitalWrite(relay, HIGH);

  Serial.begin(9600);
  Serial1.begin(9600);
  delay(1000);
  Serial.print("SIM900 ready...");
  Serial1.print("AT+CMGF=1\r");
  delay(100);
  Serial1.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);
}

void loop() {
  if (Serial1.available() > 0) {
    textMessage = Serial1.readString();
    Serial.print(textMessage);
    delay(10);
  }
  if (passFlag == 0) {
    if (textMessage.indexOf("1231") >= 0) {
      commandList();
      passFlag++;
      if (textMessage.indexOf("ON") >= 0) {
        // Turn on relay and save current state
        digitalWrite(relay, LOW);
        relayState = "on";
        Serial.println("Relay set to ON");
        textMessage = "";
      }

      if (textMessage.indexOf("OFF") >= 0) {
        // Turn off relay and save current state
        digitalWrite(relay, HIGH);
        relayState = "off";
        Serial.println("Relay set to OFF");
        textMessage = "";
      }
    }
  }
}

void commandList() {
  Serial.println ("Sending Message");
  Serial1.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);
  Serial.println ("Set SMS Number");
  Serial1.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message
  delay(1000);
  String SMS = "Enter your command!";
  Serial1.println(SMS);
  delay(100);
  Serial1.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  _buffer = _readSerial();
}

String _readSerial() {
  _timeout = 0;
  while  (!Serial1.available() && _timeout < 12000  )
  {
    delay(13);
    _timeout++;
  }
  if (Serial1.available()) {
    return Serial1.readString();
  }
}

Basically what happens with this code is that it succeeds with the password entry, but it somehow skips over the ON/OFF option select. Since I used a flag to increment the password entry (so it doesn't endlessly send me the "Enter your command" message), the loop completely stop after loop. I want to use switch case but I don't really know how to use it in this case. I don't really know how to best approach this problem, so if anyone can give some advice I would really appreciate it! BTW I'm using a SIM800L and Arduino MEGA for this


texts: Delaying pushbutton input to microcontroller while it's busy processing I/O

texts:
I am trying to create my own home automation using Arduino. I am using shift register for reading input(via push buttons) and writing output to led's. I am using SPI interface to communicate with shift registers.

Apart from SPI Arduino also deals with I2C devices. When push button is clicked Arduino ISR is invoked via pin 2, which then checks exact button that was pushed and takes action accordingly. The functionality currently works well with one small problem.

Sometimes when push button is clicked Arduino ignores the button press. After debugging for some time I observed that it happens when Arduino is busy with I2C communication with other devices.

I would like to know if it is possible to temporarily delay the push button input while Arduino busy with I2C communication? or is it possible to prioratize interrupt handling over I2C communication?

Below is the simplified code

#include <SPI.h>
#include <Wire.h>
byte Input=1;
volatile byte Check=1;
volatile byte Output=1;

int j;
//Pin connected to ST_CP of 74HC595
int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 13;
////Pin connected to DS of 74HC595
int dataPin = 11;

int interruptPin=2;

int espPin=7;

char arduinoStatus[100]="\0";

 void pin_read(){

    for(j=0; j<50; j++)
    delayMicroseconds(1000);

    Check=1;
    for(j=0; j<8; j++){
      digitalWrite(latchPin, LOW);
      delayMicroseconds(500);

     SPI.transfer(Check);
     SPI.transfer(Output);

     digitalWrite(latchPin, HIGH);

     delayMicroseconds(500);
    if(digitalRead(interruptPin)==HIGH){
      //Serial.println(Check);

      if(bitRead(Output, j)==1)
      bitWrite(Output, j, 0);
      else
      bitWrite(Output, j, 1);
    }//dig check

    Check = Check<<1;

    }

    digitalWrite(latchPin, LOW);
    delayMicroseconds(500);
    SPI.transfer(255); //to push buttons
    SPI.transfer(Output); //to LEDs

    digitalWrite(latchPin, HIGH);
    delayMicroseconds(500);

}//pin_read

void setup() {
  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(espPin, OUTPUT);
  pinMode(interruptPin, INPUT);//Input from buttons

  delay(1000);
  // the LEDs don't change while you're sending in bits:
    digitalWrite(latchPin, LOW);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  SPI.begin();
  SPI.transfer(255);
  SPI.transfer(255);
   //take the latch pin high so the LEDs will light up:
    digitalWrite(latchPin, HIGH);

    Serial.begin(115200);
    attachInterrupt(0, pin_read, RISING);

    Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
  Wire.onReceive(receiveEvent);

  Serial.println("Initialized...");
}

void loop() {
  Serial.println("Interrupting...");
 digitalWrite(espPin, HIGH);

 while(digitalRead(interruptPin)==HIGH){}
  delayMicroseconds(500);
 digitalWrite(espPin, LOW);
 delayMicroseconds(500);
 Serial.println("Done...");
Serial.print("Output:");
Serial.println(Output);
delay(3000);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  int i=0;
  Serial.println("received::");
  while (Wire.available()) { // loop through all
    char c = Wire.read(); // receive byte as a character
    arduinoStatus[i++]=c;

    Serial.print(c);         // print the character

  }
  arduinoStatus[i]='\0';
  Serial.println("###");
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
  Serial.println("Sending...");
  Wire.write("hello"); // respond with message of 6 bytes
  Wire.write(Output);
  Serial.println("Sent");
  // as expected by master
}


texts:
I've a problem with an Arduino Uno board. It only supports 140 LEDs using the FastLED library. Any LED which is higher than that number can't be turned on or off using FastLED.

Is this related to the board, the library or any other  circumstances? And help or advice would be appreciated.


texts: Increase the resistance of a photoresistor with increase in light intensity

texts:
I'm building a laser tripwire of sorts and instead of shutting up when the laser points on it (which is essential for my project) it beeps louder.

Here's the code

int buzzPin = 11; // buzzer connected to digital pin 11

void setup() {
    pinMode(buzzPin, OUTPUT); // sets the digital pin as output
}

void loop(){
    if(analogRead(0) < 750){ // this number depends on calibration of the photocell
        digitalWrite(buzzPin, HIGH); // turns buzzer on
        delay(5000); // waits for 1 second
        digitalWrite(buzzPin, LOW); // turns buzzer off
    } else{
        digitalWrite(buzzPin, LOW);
    }
}


texts:
I have a bunch of thermometers (between 1 and 128). The thermometers have an internal OneWire ID such as "28edce1e500e5" and it is not readable by humans.

Normally I would make an associative array like this:

map["28edce1e500e5"] = "Temp1";
map["28ffd33b9116420"] = "Temp2";

Serial.print(map[printAddress(allDevices[i])]);
Serial.print(" : ");
Serial.print(sensors.getTempC(allDevices[i]));

But it looks like the only hashmap library for Arduino is no longer supported and appears to be quite expensive.

The solution does not have to involve associative array.

The values are populated from a JSON file, loaded from an SD card.

I'm looking for a solutiuon to the problem, not a way to implement an associative array. (Unless that's the best way to solve the problem)


texts:
I have an arduino pro mini 5v that needs to complete 2 jobs at the same time: rotate a servo based on the data from a gyroscope, and rotate another servo based on the data from a pressure sensor. I have attempted to write code based on the protothread library (An example program can be found here: https://gist.github.com/bromagosa/8c59d9f6b5f88544fd0db1c49aab2b22)

The code, however, does not appear to be working. When it is uploaded to the board the servos kinda just glitch out and move differently than intended. I would really appreciate your help, thanks.

#include <Servo.h>
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Servo.h"
#include <pt.h>

int FSR_Pin = A0; //connected to analog 0
bool isClosed = false;

MPU6050 mpu;

int16_t ax, ay, az;
int16_t gx, gy, gz;

Servo handServo;  // create servo object to control a servo
                // twelve servo objects00 can be created on most boards
Servo wristServo;

int pos = 0;    // variable to store the servo position
int val;
int prevVal;

static struct pt pt1, pt2; // each protothread needs one of these

void setup(){
  Serial.begin(9600);
  handServo.attach(9);

  Wire.begin();
  Serial.begin(38400);

  Serial.println("Initialize MPU");
  mpu.initialize();
  Serial.println(mpu.testConnection() ? "Connected" : "Connection failed");
  wristServo.attach(8);

  PT_INIT(&pt1);  // initialise the two
  PT_INIT(&pt2);  // protothread variables

}

void handleFingers () {
  int FSRReading = analogRead(FSR_Pin);  //see whats up with the IR sensor
  Serial.println(FSRReading);                //print the value of the IR sensor

if (FSRReading > 9) {
 if (pos < 90) {
     handServo.write(pos);
      pos ++;
 }
  isClosed = true;

} else if (isClosed == true && FSRReading < 10) {
  pos = 0;
  handServo.write(pos);
  isClosed = false;
}
}

void handleWrist() {
  mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

    val = map(ay, -17000, 17000, 0, 179);
    if (val != prevVal)
    {
        wristServo.write(val);
        prevVal = val;
    }

    delay(50);

}

/* This function toggles the LED after 'interval' ms passed */
static int protothread1(struct pt *pt, int interval) {
  static unsigned long timestamp = 0;
  PT_BEGIN(pt);
  while(1) { // never stop
    /* each time the function is called the second boolean
    *  argument "millis() - timestamp > interval" is re-evaluated
    *  and if false the function exits after that. */
    PT_WAIT_UNTIL(pt, millis() - timestamp > interval );
    timestamp = millis(); // take a new timestamp
    handleFingers();
  }
  PT_END(pt);
}
/* exactly the same as the protothread1 function */
static int protothread2(struct pt *pt, int interval) {
  static unsigned long timestamp = 0;
  PT_BEGIN(pt);
  while(1) {
    PT_WAIT_UNTIL(pt, millis() - timestamp > interval );
    timestamp = millis();
    handleWrist();
  }
  PT_END(pt);
}

void loop(){

 protothread1(&pt1, 900); // schedule the two protothreads
 protothread2(&pt2, 1000); // by calling them infinitely

}


texts: Possible arduino burned (5V shorted to Vin), explanations and suggestions

texts:
Please apologize my english.
I am working in a project using an original arduino uno, one generic servo (no factory marks) and one HC-SR04 sensor.

I make a circuit like the one here: http://s24.postimg.org/43jra5l9h/mycircuit_bb.png ([url=http://postimg.org/image/lgu1p0gkh/][img]http://s24.postimg.org/lgu1p0gkh/mycircuit_bb.jpg[/img][/url], sorry, upload of image not allowed due reputation)

As you can see from the picture I accidentally connected green into Vin instead of GND. (If the image won't load, that means that my positive is connected to arduino 5V and the ground of the circuit is connected to arduino Vin)

Now my board turn on the lights but I am unable to execute the program already in the microcontroller as aslo I cannot upload a new program to it. (It gives some error message of failed to connect).

I think I burned the microcontroller(mc) by short circuiting 5V and Vin.

That said, I have three questions:

1 - Is there any way to find out if I really burned my board using just a low budget multimeter? And if I did, which parts I need to replace?
I have access to some spare ATMEL mc and I think I could replace and reprogram them by using another arduino board. However, I am affraid that I may have burned few other items and just by replacing the mc will not give me back all the funcionallities of a new board.

2 - I have basic knowledge of electronics, could someone explain to a beginner like me which impact did that mistake could/have make in all components of the circuit? (Arduino board, the servo and the sensor)

3 - Even before the accident, the circuit just work well for few minutes. I read tons of pages and tried a lot of suggestions, most of them related with power supply (capacitors to avoid flutuations, One battery just for the servo, one battery just for the sensor...) and none gave me good results.
I am wondering what are the alternatives to power up this simply circuit, in particular I am looking for this possibilities: Complete external power supply (by using AC to DC adapters), Complete internal power supply (Using just batteries) and a mix of those two (Using AC to DC and batteries). I have no access to a external DC power supply generator other than batteries.


texts:
I have a custom Arduino ATMega328 board that generally runs at 5V @ 8MHz (using the Arduino Pro 3.3V 8MHz profile and bootloader). The main reason I'm using this setup is so that I can put the board to sleep when main power is disconnected and it starts being run off of battery power (3V from a coin cell). The 5V and 3V sources are diode OR'ed together and the 5V input is tied to INT0. In code, when it detects that INT0 has fallen low, it initializes sleep mode and everything powers down with the exception of the watchdog timer that keeps a 1Hz cycle to keep an internal count and check it the chip should be woken back up. This works beautifully when 5V power is applied first, then the battery is inserted, then 5V is disconnected. It goes to sleep and when 5V is brought back it wakes up and I can see it hasn't lost count.

However, the problem comes when 3V is applied first. I'm honestly not sure if it's even booting. But what it is supposed to do is boot, check if INT0 (Digital 2) is low and, if so, go right to sleep. By watching the current draw I see that it powers up to a few mA for a couple seconds, then drops to about 0.3mA (still higher than it should be in sleep mode). But when I re-apply 5V, nothing. The power draw goes back up but it is unresponsive (over FTDI serial).

Is there maybe something I'm missing that it can't be booted on 3V... in theory it should run just fine.

Update: I dropped an LED onto D13 and tried the blink sketch. Works fine when starting from 3V or 5V. However, when I run my firmware and start it from 3V, the LED just starts flashing wildly. I have no idea what's causing it since I never even setup D13 as anything in my code. But it makes me thing it's something to do with the bootloader...


texts: SoftwareSerial together with AltSoftSerial and HardwareSerial

texts:
The title says it all.

Angone with experience here on this subject?

I want to use all Hardware serial, SoftwareSerial and AltSoftSerial on Arduino Duemilanove with At328.

Is it possible?