texts: Control speed of a dc motor with a 9v battery

texts:
Problem:
I want to have a 9v battery that powers a dc motor. I want to control it with a bluetooth remote that has 3 buttons. 1st button is turn the motor with 1.5v, 2nd button is motor off and the 3rd button is full power (9v). Here is the problem normally I will change volt with my arduino using code, but it has a max voltage of 3.6v so I can't control the battery with the arduino. Also I would like the 9v battery to power the arduino and bluetooth module if that is possible, so I have only one battery that powers everything.

What I tried:
I found a lot of different things on the internet. Pwm, Tip120 transistor, L298N and it only confuses me more I have no idea where to start. Spend 8 hours looking for stuff and no step further.

Result:
I hope everything will work with a 9v battery and the bluetooth remote can switch between 3 different speeds.![enter image description here]


texts: Hex String -> Byte Array -> Serial Write

texts:
I'm writing code that I discussed in a previous post. I now have a setup where I send my Arduino an ASCII-encoded Hex String that represents the bytes I want to write to my serial device. I think I've got most the code figured out other than the way to best convert the hex string for sending

This Code is working

void SendCTRL (String &input)
{
  const char *hin = input.c_str();    // Get character array
  int clen = input.length()/2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
  RS485Serial.write(cmd[i]);   // Send string someplace
  }
  delay(clen/4);
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
  Serial.println();

}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

From what I understand something along the lines of char ISS = SubS.GetBytes(), but guidance would be appreciated


texts: Access I2C sensor from Arduino Uno as slave

texts:
I connected Raspberry Pi 3 to an Arduino Uno through I2C. The Arduino Uno uses the I2C as slave.

When I connect AM2320 sensor (temperature and humidity) to the Arduino Uno, I am getting the response that the sensor is offline.

I tested the sensor on Raspberry Pi 3 and it is working fine. On the Raspberry Pi the address is 0x5c. On most libraries, the address is 0xb8. I have the same result when I tried these 2 addresses.

Do I have problem because Arduino Uno is working as slave?


texts:
I have loaded an example sketch that came with the installation of the Arduino software onto my Uno.

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

void loop() {

  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

From this time TX light is continuously on. It's remaining on even after resetting it. How do I end void loop so that TX light goes off.


texts: Writing Data through Pin at certain frequency

texts:
I have an Arduino UNO which is connected to an KLZ25 board, the Arduino sends an 1MHz Clock at Pin 9 and now I should write the PDM-Data with 1 Mhz at pin 8. But i don't know how to write with such a speed, because if I write in the Loop:

loop{
digitalWrite(1);
digitalWrite(0);
}

I get only a frequency of 36Khz, I know it depends on the count of commands in the loop, but I don't know how to write with a certain frequency in my case 1Mhz.

I get the PDM-Data (pulse density modulation) in form of 1 and 0 from a python script on a Host-PC and now I want to stream the Data with 1MHz to an other developer board which makes further calculation with the PDM-Data. I store the PDM-Data in queues because I have not enough memory to store the whole Data.

Does anybody know how to write PDM-Data with a 1MHz frequency to an output pin ?


texts: Arduino sketch taking forever to upload, followed by multiple issues

texts:
I am using Arduino Uno board with Windows 10. From the tutorials on Arduino website, I am trying to upload the following code:

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

It had undergone a series of issues:

First,
avrdude: ser_open(): can't open device "\\.\com3"

I searched for his issue, and found that most common solution id to go to device manager and change the name of the port, then unplug and plug again the arduino board. I did that

Second,

C:\Program Files (x86)\Arduino\hardware\tools\axr\bin\avr-ar:
unable to rename 'core.a'; reason: file exists\\

I thiught it could be a memory problem. I used the reset button on the board, and repeated steps from the solution to the first problem. I tried to upload the code again.

But now, I am not getting any error message. But the problem is that it is taking forever to upload the code. I see Uploading... status since a long while. The green progress bar is also complete, but no uploading completed till now.

Any help to understand and solve this will be appreciated.


texts: Two floating point values do not get added and printed on ESP-WROOM-32

texts:
I have a Olimex ESP32-PoE board which has a ESP-WROOM-32.

I just found out a strange behaviour for printing floating point numbers on the board.

Sketch

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  float a=34567891.234;
  float b=2.3456;
  a++;
  Serial.print(a+b, 4);
  Serial.println("");
  delay(1000);
}

the sketch is extremely simple where I want to add two floating point numbers, one a big and another small to print their addition result upto 4 places.

Output

on the serial console in the Arduino IDE

34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000

Everytime I increment the float a using a++ i expect it to increment by one and print the result but the output above is completely off.

Without Increment

void loop() {
  // put your main code here, to run repeatedly:
  float a=34567891.234;
  float b=2.3456;
  Serial.print(a+b, 4);
  Serial.println("");
  delay(1000);

}

output

34567896.0000
34567896.0000
34567896.0000

Same output.

Is this Board specific or is the Serial.print not supporting float?


texts: Is it possible to transmit Longitude and Latitude via RF433MHz?

texts:
I want to make a drone project, and to that I will use arduino as the platform. My plane is to use a Play Station controller to control the Drone in the air. In addition to that I want to connect a GPS-module. My question goes, is it possible to transmit the longitude and latitude from the GPS via the RF 433MHz to the receiver? When received the longitude and latitude how can I transmit them further to the Smartphone and display the data on google maps? I suggest it could be possible through the Xbee, but I am not sure.

I would like if someone can confirm my idea, if not bring me a better way to do that.

In the image below, you can see the diagram of my design.


texts:
Everything i read about the chinese Digispark attiny85 clones says you can use p0-5 as digitlal I\O (p5 as after fuse reset)
Simple test code for a button will not let me use P1 as an input tied to a simple button.
The code below works on p0,p2,p5 but will only interrupt the LED that is set to on, on P1.
#include "DigiKeyboard.h"

//pins 3 & 4 used for usb connection
bool buttonState1 = 0;

void setup() {
  pinMode(1, INPUT);
  digitalWrite(1, HIGH); //turn on pull-up resistor
}

void loop() {

    if (digitalRead(1)!= buttonState1){
      buttonState1 = digitalRead(1);
      if (buttonState1 == LOW)DigiKeyboard.print("test1");
    }

}


texts: Formula for decision making when in contact with an obstacle using Arduino

texts:
I am currently working on an obstacle avoidance robot project and I have seen numerous algorithms for obstacle avoidance a very good example is this Obstacle avoidance algorithm [Editor's note: by user3880651],
but unfortunately non of those algorithm works with Arduino so upon my research I found this blog

and in there the author talks about an effective way to avoid obstacles and even has a formula he uses for avoiding obstacles at different positions e.g (Front and sides) but doesn't really explain how he got the formula so I was wondering if anyone as an effective formula or algorithm for obstacle avoidance that works with Arduino thanks for your help in advance


texts: Can the Arduino Mega2560 use the New Haven NHD-0420D3Z-NSW-BBW-V3 LCD panel by controlling it with the New LiquidCrystal library? What cable will you use to connect the LCD to Arduino, are there screw terminals on the LCD board to secure the connections? It seems like only 4 connections are needed, for GND, VCC, SDA, SCL.


texts: How to pass a string pointer to a function

texts:
I'm working on a project, where I wish to use pointers. I had a very quick overview of using pointers in C in collage, but I don't know how to use them.

I want that function uses input String (answer) as pointer.

Calling function in setup block

void setup() {
    sendCommand("AT+RST\r\n", 5000, DEBUG, "ready");
    sendCommand("AT+CWSAP_CUR=\"mega\",\"password123\",10,3\r\n", 4000, DEBUG, "OK");
}

String sendCommand(String command, const int timeout, boolean debug, String *answer)
{
    String response = "";

    Serial1.print(command); // send the read character to the esp8266

    long int time = millis();

    while ((time + timeout) > millis())
    {
        while (Serial1.available())
        {
            // The esp has data so display its output to the serial window
            char c = Serial1.read(); // read the next character.
            response += c;
        }

        //Waiting for the right answer and breaking a while loop
        if (response.indexOf(*answer) > 0)
        {
            break;
        }

    }

    if (debug)
    {
        Serial.print(response);
    }

    return response;
}


texts:
I have an ethernet shield on an Arduino Mega 2560. I am running the code below. This is a slightly modified version of the DHCP ip printer example, namely I am setting a static IP instead of DHCP.

I was expecting to get:

Start Ethernet
My IP address: 192.168.178.163.

on the serial monitor. Instead I got:

Start Ethernet
My IP address: 0.237.237.237.

Any idea what the reason might be? If I am using DHCP (the unmodified example, commented lines in the code below), the code seems to freeze on the Ethernet.begin() call.The "Failed to configure ..." is not even printed.

Here is the sketch:

#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, 0x10, 0xC1, 0x2C
};
byte ip[] = {192, 168, 178, 163};

// 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 native USB port only
  }

  Serial.println("Start Ethernet");
  // start the Ethernet connection:
  Ethernet.begin(mac, ip);
  /*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:
  printIPAddress();
}

void loop() {

  switch (Ethernet.maintain())
  {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");

      //print your local IP address:
      printIPAddress();
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");

      //print your local IP address:
      printIPAddress();
      break;

    default:
      //nothing happened
      break;

  }
}

void printIPAddress()
{
  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();
}

The situation is similar to Ethernet shield not getting IP, but I checked that all pins are connected properly. Also setting pin 10 to high does not change anything.


texts:
I am a complete newbie with matlab and as well arduino, so thanks for your patience :)
I am trying to display live data from a groove microphone and convert the voltage into decibels. I would also like to be able to have a moving x axis, where the time is shown of the programm collecting the data, for example actual time -15seconds.
I am also not quite sure on how I could smooth the data that I get from my microphone as it's very noise and using smoothdata and its various methods has not been that helpful somehow.
Here is my MWE attached

plot real live data
have a moving x-axis so there are only 15 seconds of data on screen
smooth my data to something usable

Many thanks for your help!!


texts: HC-06 Bluetooth RX & TX voltage (3v3 || 5v)

texts:
I acquired a HC-06 Bluetooth module, and understand that the voltage on the pins must be 3v3 and therefore requires the use of a voltage divider to lower the Arduino's 5v to 3v3 like this.

But the page where I purchased the product says the following:

  interface level 3.3V, you can directly connect a variety of SCM (51, AVR, PIC, ARM, MSP430, etc.), 5V microcontroller can also be directly  connected, it can not pass without MAX232 MAX232!

Does this mean I can connect without using a voltage divider?

What does "it can not pass without MAX232 MAX232!" mean?


texts: Read time digits from DS1307 and run code based on return

texts:
I am currently reading a DS1307 adafruit breakout board and I need to drive two nixie tubes from a shift register. The shift register is running two 74141 IC chips. I have code that loops through all the nixie digits one at a time with a delay of 1 second between each. Now I need to write some code to pull min, hour, and second and change the shift register low/high outputs to display the correct nixie digit. I have the DS1307 returning the correct time on my com by using

 Serial.print(now.hour(), DEC);
 Serial.print(now.minute(), DEC);
 Serial.print(now.second(), DEC);

However, I am not sure how to dimension a string, set that string equal to the two digits on the hour, minute, or time, and then divide the two digits and write if statements to correctly display the tubes. I am used to VB.NET and now C coding.

=======================UPDATE=======================

I am using this code to set any individual digit of the nixie tube to on.

       //Turn on 0
 sr.set(4, LOW);
 sr.set(5, LOW);
 sr.set(6, LOW);
 sr.set(7, LOW);

The sr is the shift register and each number is which leg of the shift register I am turning low or high. This specific piece turns on the digit 0.


texts: Cannot make sense of values from Bluetooth HC-01

texts:
I have a simple script that listens on pin 0 for input, and if it gets anything, it Serial.prints it. But I cannot make sense of the results. I have a basic app that sends text over Bluetooth (in the code I see utf8.encode(message) if that helps), and I'm able to validate that the message is not corrupted by the module, by simply touching the RX and TX pins together, the app receives the same message it sent. But the Arduino cannot understand it.

Here's my code:

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

void loop() {
    if (Serial.available() > 0) {
        Serial.print("New value: ");
        Serial.println(Serial.read());
    }
}

The TX on the HC-01 is connected to pin 0, and the RX is connected to pin 1. Power and ground are connected to the Arduino's (and I even tried different grounds just in case that one was fried). The Arduino is powered by USB and I'm using the Serial moniter. Here is some sample input-output:

Me through the app: a. Arduino: 255
Me through the app: a. Arduino: 254
Me through the app: a. Arduino: 254
Me through the app: a. Arduino: 254
Me through the app: a. Arduino: 254
Me through the app: a. Arduino: 255
Me through the app: aa. Arduino: 254
Me through the app: aaa. Arduino: 252
Me through the app: aaaa. Arduino: 252

I just don't understand any of it. Please help me out.


texts: Im trying to get a 3 button password sequence working

texts:
I'm trying get a password system working that when you click 3 buttons in a certain order (1, 2, 3, 3, 1) then an LED will light up. But as I'm going to implement this into a larger code I can't just have the void loop() going forever to wait for it.

I think my issue is in the while loops and making it wait for one of the buttons to be pressed but I don't know how to get it to work.

thanks

#define greenLED A0
#define redLED A1

int button1 = 5;
int button2 = 4;
int button3 = 3;

void setup() {
  // put your setup code here, to run once:
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(button1, INPUT_PULLUP);
  pinMode(button2, INPUT_PULLUP);
  pinMode(button3, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly:
  int total = 0;
  while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
    while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
      while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
        while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
          while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
            if(digitalRead(button1) == HIGH){
              total = total + 1;
            }
          }
          if(digitalRead(button2)==HIGH){
            total = total+1;
          }
        }
        if(digitalRead(button3)==HIGH){
          total = total + 1;
        }
      }
      if(digitalRead(button3)==HIGH){
        total = total+1;
      }
    }
    if(digitalRead(button1) == HIGH){
      total = total+1;
    }
  }
  if(total == 5){
    digitalWrite(A0, HIGH);
    delay(2000);
    digitalWrite(A0, LOW);
  }else{
    digitalWrite(A1, HIGH);
    delay(2000);
    digitalWrite(A1, LOW);
  }
}


texts: Restart sequence of NeoPixel stick with a push button at any time

texts:
I am really happy with my new Arduino stuff and playing around with all those pixels :).

I am new to programming and it's difficult to understand it, but with every success, I grow in knowledge.

My latest problem now is to restart my loop of incrementing the strip at any time with the push of a button.

I know that delay(); will stop the code completely and wait till the time passes, but I wrote some code without the use of delay(); and used millis(); instead.

So far my LEDs are incrementing through my strip, but I am not able to restart it until it passes though completely. I read that the while(); part in my code works kinda like a delay(); and that would prevent it from restarting until a full cycle. I used some millis(); code from a different sample so it's not like the ones from Blink Without Delay.

I searched so many sites and cannot write another code to increment without a delay, so hopefully you can help me with it.

#include <FastLED.h>

#define NUM_LEDS_PER_STRIP 16
CRGB ledStrip[NUM_LEDS_PER_STRIP];

const int signalButtonPin = 4;
const int ledStripPin = 8;

int buttonState = 0;
int lastButtonState = 0;

int delaySignalAnimation = 100;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;

void setup() {
  pinMode(signalButtonPin, INPUT_PULLUP);
  pinMode(ledStripPin, OUTPUT);
  FastLED.addLeds<NEOPIXEL, 8>(ledStrip, NUM_LEDS_PER_STRIP);
}

void loop() {
  buttonState = digitalRead(signalButtonPin);
  if (buttonState != lastButtonState) {
    if (buttonState == LOW) {
      fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
      for (int i = 0; i < 16; i++) {
        ledStrip[i] = CRGB::Blue;
        FastLED.setBrightness(100);
        FastLED.show();
        currentMillis = previousMillis = millis();
        while (previousMillis + delaySignalAnimation >= currentMillis) {
          currentMillis = millis();
        }
      }
    } else {
      lastButtonState = buttonState;
    }
    fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
    FastLED.setBrightness(0);
  }
  FastLED.show();
}

Thanks in advance for you help.


texts: help connecting atmega32 micro-controller to LAN

texts: I have an atmega32 micro-controller and I would like to connect it to my LAN via ethernet, I'm planing to do this using arduino ethernet shield W5100 but I don't know how to start or how to interface it or code it, I need help finding a step-by-step tutorial to do that if it's possible or help to find a better solution if using arduino ethernet shield may cause problems, thanks in advance.


texts:
I have a project where we need to create a virtual cane for blind people and it will have 3 functions:

Pressure button when pressed will connect to an android phone through HC-06 Bluetooth modulo to an app that I developed and will
can to someone that I defined
Temperature sensor that is attached to a buzzer that will buzz if the
temperature is higher than 40 Degrees
Ultrasonic sensor attached to and vibration motor that will vibrate
if there is any object less than 70 cm from the person.

When I combine the code from the ultrasonic and the temperature sensor, everything works fine, when I add the bluetooth code, nothing works, anyone see the problem? Or could you show me the problem and solveit?

Code without Bluetooth:

int DHT11_PIN=8;
dht DHT;
int buzzer=6;
int trigPin=3;
int echoPin=2;
int motor=7;

void setup(){
  Serial.begin(115200);
  pinMode(DHT11_PIN,INPUT);
  pinMode(buzzer, OUTPUT);
  delay(5000);

  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(motor, OUTPUT);
  delay(5000);
}

void loop(){
  Stemperature();
  Sultrassom();
}

// sensor de tempratura e Buzzer-------------------------------
void Stemperature(){
  digitalWrite(buzzer,LOW);
  DHT.read11(DHT11_PIN);
  float t=DHT.temperature;
  Serial.print("Temperature = ");
  Serial.println(t);

  if (t>40){
    digitalWrite(buzzer,HIGH);
    {tone(6,100,20);
    delay(1);
    noTone(1);
    delay(1);
    }
    delay(1000);
    Serial.print("ON T=");
  }else{
    digitalWrite(buzzer,LOW);
    Serial.print("OF T=");
  }
}

//Sensor de Ultrassom e Motor vibração-----------------
void Sultrassom(){
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) * 0.0340;
  Serial.println(distance);

  if (distance < 70){ // se a distância for menor que 70 cm o motor vibra
    digitalWrite(motor,HIGH);// quando a distância for menor que 70 cm
    Serial.print("MOTOR ON=");
  }else{
    digitalWrite(motor,LOW);// quando a distância for maior que 70 cm
    Serial.print("MOTOR OFF=");
  }
  delay(5);
}

Bluetooth Code:

const int buttonPin = 4;     // the number of the pushbutton pin
boolean buttonState;         // variable for reading the pushbutton status

void setup(){
  Serial.begin(9600);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  buttonState = LOW;
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if(buttonState == HIGH) {
    // send char 1 via Bluetooth:
    Serial.println("1");
    delay(20000);
    while (0);
  }
}


texts: Issue with Embedded Coder Target for Arduino

texts:
I am using the embedded coder target for arduino following this: (http://www.mathworks.com/matlabcentral/fileexchange/30277-embedded-coder-target-for-arduino). I am having problem while running the myarduino_blink.slx demo.

My MATLAB version is R2015a, and I am using an Arduino Uno. I ran the file setup_custom_target_arduino.m after changing the relevant directory listing and the arduino version in the m file, and I got the output of Arduino on COM 3, which was correct.

After this, I checked the Simulink Library Browser and I had the Custom C/C++ Target Arduino Library will all its modules. Now when I simulate the model, I get the following error:

Error in S-function 'myarduino_blink/Digital Output':
S-Function 'sfunar_digitalOutput' does not exist

Kindly help me out, what could I have done wrong?


texts: How to create a smooth change in voltage?

texts:
We are given two voltages A and B between 0 and 5V.
So how do I generate a smooth/continuous analog change in
voltage from A to B in a predefined time? The current with that varying voltage is 1 ma or less. The output voltage value is described by a simple quadratic (aX^2)+(bx)+c, at time x seconds.

If that not possible using an Arduino - what is the nearest  solution to it? It seems that it would require an RC circuit?

When I mean smooth/continous I mean it doesn't move in "digital steps" or to use an analogy with resistance instead of voltage - it would be like the way resistance changes when a potentiometer is turned between two places, in a given time, by hand.

A potential solution would be to make a circuit that generate arbitrary voltage between 0 and 5v, some how, at a point in time. For each subsequent small change in time, the change in time is constant, generate the desired voltage from a sketch. If the change of time is small and constant, will putting in a high pass RC filter work? Though I'm not sure of a circuit that can create an arbitrary voltage, or arbitrary voltage resolution or how good the RC filter approximates the quadratic smoothness. I don't know the answer.


texts:
I have a code that reads the value of a sensor and because it needs to be very fast it does not use digitalRead but a strange form of reading. In the top of the code it shows:

#define IRSENSOR PIND
int irpin = 2;

I have no idea why this PIND referes to my arduino pin 2, but it only work if my sensor is in pin 2. If I want to change to pin 9 and only change the irpin varialbe it does not work. Why?

To read the sensor I use this code:

while (IRSENSOR & (1 << irpin )) {

Have no idea why this work. Does anyone know this kind of programming with arduino?


texts: Are these GND connected resistors on the Arduino Due redundant?

texts:
Does anyone know why these 4 resistors are there (attachment)? It seems like they are useless since connected in a loop to GND.
Full schematics here: https://store.arduino.cc/arduino-due


texts: How to find how much data in the transmit buffer?

texts:
How do you find how many bytes are currently waiting in the transmit buffer?

I'm trying to diagnose a weird serial disconnection problem with an Arduino Uno and a rosserial node. It works fine for 10-20 minutes, and then mysteriously losing connection. At first, I thought the Arduino was running out of memory, but I'm able to use the MemoryFree library to log available memory, and it never drops below 9051 bytes.

I now want to make sure the problem isn't because the serial buffer is overflowing, from the Arduino trying to send too much data.


texts: How to split 12V power suply to arduino and led matrix panel

texts: I'm trying to build my Arduino project with Arduino mega and led matrix panel. I'm wondering what power supply should I buy, my first thought was to power the matrix panel from a 5v Arduino pin, but I read here that it's not really a good idea. So now I'm wondering if I can buy a 12V power supply and somehow split it to 6V and 6V (or something like it). To connect one end to Arduino and the other to the matrix panel. If it's possible, how do I do that? Thanks for any help!


texts: Are there any standard ways of reporting a runtime error?

texts:
I'm new to Arduino but I'm an experienced programmer. I'm wondering if there are any common functions for reporting errors in Arduino programs? For example, in JavaScript we have the alert() function, or on Unix you can write a message to standard error and exit.

Ideally, if the serial port is available then an error message would be printed there, or if there is an LED then maybe we should blink it. This would need to be configurable based on what the programmer wants to do with available hardware.

Looking the example sketches, error reporting seems pretty horrible. I'm wondering if any libraries handle this better?


texts: Linear actuator jitters/vibrates when getting PWM from Arduino Mega 2560 through JKR 21v3 motor controller

texts:
I recently bought this linear actuator and motor controller from Pololu:

Linear actuator
Motor Controller JRK21v3

There are several steps that I have to follow in order to set this thing up before I can test it. These instructions can be found here: Pololu JRK USB Motor Controller User’s Guide » Setting Up Your System

I would like to program this using PWM method because I would like to keep the Serial RX for other sensors.  From my little experiment, by using a potentiometer, I noticed this pattern:

Position: Voltage

Fully extended : 0 V
At Rest : 2.35V
Fully Retracted  : 4.77V.

For this system, I will be controlling it using a PS2 controller. So, by using only the Y_axis of the analog joystick of a PS2 Controller (Up: 0, Rest: 128 and Down: 255), I program it as follows:

//Move Linear Actuator with PS2 on JRK21v3 Controller

#define pwm 6           //red wire
#define dir 7           //yellow wire

//PS2 controller
#include <SoftwareSerial.h>
#include <Cytron_PS2Shield.h>

Cytron_PS2Shield ps2(10, 11); // SoftwareSerial: Rx and Tx pin

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

  ps2.begin(9600);
  Serial.begin(9600);
}

void loop()
{
  int Y_axis = ps2.readButton(PS2_JOYSTICK_RIGHT_Y_AXIS);  // 0 - 255
  Serial.print("Y_axis:");
  Serial.println(Y_axis);

  analogWrite(pwm, Y_axis);
}

When I tested it, the linear actuator jitters/vibrates when it is at rest position. What could possibly cause this? Is it the duty cycle due to the PWM? How can I fix this or are there any other better methods?


texts: Why is 8x8 matrix pins do not correspond to rows and columns order?

texts:
It would be easier to program led matrix if 1-8 pins corresponded to 1-8 rows and 9-16 pins corresponded to 1-8 columns.
Instead there is the following arrangement:

Why is it made like this?


texts: Script stops functioning after calling irsend() function in irlibrary!

texts:
I have the following script which checks if the user has pressed the numbers "770" or "769" continuously in the remote. The script works fine and displays all numbers. When I press the buttons "770" or "769" continuously the function powerOff() is called and I get no serial input.

/*
 * IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Version 0.1 July, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 */

#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

IRsend irsend;

decode_results results;

int intValue;
String strValue;
String str3;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    intValue = results.value;

    Serial.print("Integer value : ");
    Serial.println(intValue);

    strValue = String(intValue);
    Serial.print("String str : ");
    Serial.println(strValue);

    Serial.print("Length : ");
    Serial.print(strValue.length());
    Serial.println();

    if(strValue.length() <= 1){
      str3 += strValue;
      Serial.println(str3);
       // Receive the next value
   }

    delay(200);
    irrecv.resume();
  }
  //Serial.println(str3);
  if(str3.endsWith("770")){
    powerOff();
    str3 = "";
  }
  else if(str3.endsWith("769")){
    powerOff();
    str3 = "";
  }

  else{}
  //powerOff();
}

void powerOff(){
    irsend.sendRC6( 0xC0000C, 24);
    irrecv.resume(); // Receive the next value
}


texts:
I'm using Arduino nano and I'm struggling working with the DRV8870 IC on PWM mode.
When I use analogWrite(_pin, duty_cycle); the motor makes weird noises.
I thought it's because of the PWM frequency so I tried to change it using
TCCR1B = TCCR1B & B11111000 | B00000011; but it didn't work out.
Texas Instruments wrote this in their pdf:
"When using PWM, switching between driving and braking typically works best. For example, to drive a motor forward with 50% of the maximum RPM, IN1 = 1 and IN2 = 0 during the driving period, and IN1 = 1 and IN2 = 1 during the other period."
drv8870_pdf


texts:
I tried to connect two modules that require I2C connection and they won't work at the same time.
I used the Arduino Sensor Kit - Base. This kit does not need any connection, you just have to code to get your desired output. I wanted to display the Air Pressure (BMP280) module values to the 0.96" OLED Display, however, it is refusing to run both the air pressire and the OLED display at the same time. Only running one module (either Air pressure or OLED) at a time makes it work. Does it have something to do with how the I2C connection is wired on the board?
#include "Arduino_SensorKit.h"

void setup() {
  // put your setup code here, to run once:
  Oled.begin();
  Oled.setFlipMode(true);
  Oled.setFont(u8x8_font_7x14B_1x2_r);

  Pressure.begin();
}

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

  Oled.setCursor(0, 10);
  Oled.print("Temp: ");
  Oled.print(Pressure.readTemperature());
  Oled.print(" C");
  Oled.setCursor(0, 20);
  Oled.print("Pres: ");
  Oled.print(Pressure.readPressure());
  Oled.print(" Pa");
  Oled.setCursor(0, 30);
  Oled.print("Alti: ");
  Oled.print(Pressure.readAltitude());
  Oled.print(" m");

  delay(1000);
}

What I did:

Test to see if Air Pressure will still work while both Air Pressure and OLED is connected by using Serial.begin(). Now I know that only the OLED does not work when both modules are connected.
Changed order of initialization. Same result: Air Pressure works but not OLED


texts: How can I wire a 12V LED switch so that it is powered, but my Arduino only receives a 5V signal?

texts:
My arduino is powered by 12V.  I am getting some cool looking 12V led switches from amazon, but they need 12 volts to light up. My arduino will perform an override function when it detects the switch is closed. the digital pins can only handle 5V. How can I step down the 12V signal that powers the switch to the 5V that the pin can handle.

12V supply -> 12V led switch -> reduce 12V to 5V -> arduino digital pin


texts: Get accelerometer values from BNO055 using adafruit's Unified Sensor Library

texts:
If I understand correctly using the Adafruit_Sensor one can extract information from the sensor specific information. These sensors are currently mentioned in the README. I am using the BNO055 for two things:

Orientation values (Heading, pitch, roll)
Linear Acceleration values

My code is similar to the Example mentioned Adafruit_BNO055's bunny

Code

I tried the following in my loop()

void loop() {
  // put your main code here, to run repeatedly:
  sensors_event_t event;
  bno.getEvent(&event);

  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.x);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.y);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.z);
  Serial.println(F(""));

  Serial.print(F("Acceleration: "));
  Serial.print((float)event.acceleration.x);
  Serial.print(F(" "));
  Serial.print((float)event.acceleration.y);
  Serial.print(F(" "));
  Serial.print((float)event.acceleration.z);
  Serial.println(F(""));

  delay(BNO055_SAMPLERATE_DELAY_MS);
}

Created sensors_event_t event and used the orientation and acceleration parameters to obtain the orientation and acceleration values in x, y, z directions.

output

The orientation and accleration values are the same:

Orientation: 105.50 -20.56 -101.00
Acceleration: 105.50 -20.56 -101.00
Orientation: 97.81 -14.69 -119.56
Acceleration: 97.81 -14.69 -119.56
Orientation: 93.81 -10.94 -125.56
Acceleration: 93.81 -10.94 -125.56
Orientation: 94.44 -12.25 -122.56

I tried adding another event event1 in the loop() but I still get the same results

sensors_event_t event;
  bno.getEvent(&event);

  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.x);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.y);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.z);
  Serial.println(F(""));

  sensors_event_t event1;
  bno.getEvent(&event1);
  Serial.print(F("Acceleration: "));
  Serial.print((float)event1.acceleration.x);
  Serial.print(F(" "));
  Serial.print((float)event1.acceleration.y);
  Serial.print(F(" "));
  Serial.print((float)event1.acceleration.z);
  Serial.println(F(""));

  delay(BNO055_SAMPLERATE_DELAY_MS);

Can't the BNO055 along with the Adafruit_Sensor library not provide the acceleration and orientation values as events or is the library used only to obtain orientation values from the BNO055?


texts: How to connect Mg995 and arduino nano since nano can only output 40mA at max?

texts:
Datasheet for Mg995 shows:

Current draw at idle 10MA
No load operating current draw 170MA
Stall current draw 1200MA

Maximum current that an arduino nano can output is 40mA.
So, what intermediary component should I use to make the connection between the two work?


texts: How to convert digital signal to analog value

texts:
I have spwm output from arduino, and when i read on analogread it shows only 1023 and 0, because it is digital signal.
Is there any way to convert these spwm value into analog value reading


texts: No Device Found On Bare-bones SAM3X Chip

texts:
0

I've been trying to make my own board with a SAM3X and W5500 (Arduino Ethernet Shield) on it with those two chips connected via SPI.

From the Arduino Due Board, most of the stuff, we don't need. So obviously, almost everything went off. Particularly, I remove the power switching circuits since we won't be varying power anyway. The native USB Programming also went off as well as the Programming port circuit.

I've only left headers so I can connect the 16U2 (with 16MHz crystal) circuit externally. Headers are VIN (5V from USB), RX (from a level shifter), TX and Ground. I'd not included the reset signal so from the 16U2 pin, I connected a 1kohm resistor (R23) to the reset line in my board.

The 16U2 I have externally is programmed with the new file in

https://github.com/arduino/ArduinoCore-sam/tree/master/firmwares/atmega16u2

When I connect the 16U2 circuit to my USB Port, I was able to see it as the programming port correctly. However, when I try uploading a sketch to the board (sample blink), the IDE says No Device Found on the COM port.

I've tried using bossac and modifying the COM port thru command prompt but I still get the same result.

I've checked the SAM3X checklist and it says there that for SAM-BA to boot, I only need to have the correct supplies and the 12 MHz Crystal Oscillator. I've checked everything using multitester and all the supplies are in the correct voltage. I've checked the crystal using an oscilloscope and I can see that it outputs the expected waveform.

I've also checked the TX and RX line from the 16U2. There are data being send by the 16U2 but the SAM3X is not responding.

One thing I notice is that the 32 kHz crystal is not working. But from what I've read in these forum, that is not powered by the SAM3X until the slow clock oscillator is enabled to be externally sourced.

The last thing I think that I've done different is that I'd connected the VBUS pin to the 3.3V supply rail where it was directly connected to the USB power. The reason I've done this is because I'm not using USB anyway.

Also, the data lines for the native USB, I've terminated them using 1MHz resistors to ground just so they're not left flaoting.

Are these (VBUS and datalines) causing my SAM3X to not reply and properly work so sketches can be uploaded? Would want to confirm VBUS first before destroying the trace in my board as I'm afraid I might fry the SAM3X chip with 5V.

Are there other things I've done wrong?


texts: What makes a board "Arduino Compatible"?

texts:
There are all sorts of Arduino and Arduino-compatible boards out there. They come in all form factors and they come with all sorts of different I/O. They even come with memory specs and different kinds of microcontrollers, from the ATmega328P to Intel-based.

So what is it that imbues a board to become "Arduino Compatible" ? Must it be pin-compatible? Must it be possible to compile Arduino source code for the board? Or must the board be binary-compatible? Must it emulate some specific processor instruction set?

Very curious. Please reference specifications if possible. Thank you.


texts: Working or functionality of pinMode(), digitalWrite() and digitalRead()

texts:
I'm a newbie in Arduino. I find out a couple of examples.

Here, below arduino simple code I just uploaded.

Here, what is functionality or working of pinMode, digitalWrite and digitalRead ?

const int kPinLed = 7;
const int kPinBtn = 8;

void setup()
{
  pinMode(kPinLed, OUTPUT);
  pinMode(kPinBtn, INPUT_PULLUP);
}

void loop()
{
  if(digitalRead(kPinBtn) == LOW)
  {
    digitalWrite(kPinLed, HIGH);
  }
  else digitalWrite(kPinLed, LOW);
}


texts: Why all unset pins of my Arduino Uno are outputting 2 volts?

texts:
I am new to Arduino and physical computing When I measure the wire coming from any UNSET Arduino uno pin, the result is approximately 2 volts even the "ANALOG IN" pins. Considering that the pins which been set to HIGH and LOW are giving 5 and 0 volts "which is cool".
Is that the nature of Arduino or is that a failure caused by short or anything else?


texts: How to flush the input serial buffer in Arduino?

texts:
I am communicating with the esp8266 WiFi module using Arduino. The module returns GET requests from other clients. They will be of the form

GET /101011 HTTP/1.1\r\nHost...

I wish to extract only the 101011 from the received serial data and discard the rest. I came up with this small chunk of code to test it by sending data from my laptop.

This is the code:

String s;

void setup() {

  Serial.begin(9600);
}

void loop() {

  if(Serial.available())
  {
    Serial.println("Inside");
    Serial.find("/");
    s = Serial.readStringUntil(' ');
    Serial.println(s);
    // Discard the rest of the data . Snippet from Jeremy Blum's Blog

    while(Serial.available()>0) Serial.read();

  }

}

Jeremy's Blog

But when I run this using the input GET /101011 HTTP/1.1\r\n the output produced is

Inside
101011
Inside
1.1\r\n

Why is Serial.available() returning true even after reading everything? How to discard the rest of data from the serial input buffer?


texts: Error while uploading the sketch for Arduino Mini

texts:
I'm having a problem while uploading the program.

Arduino: 1.8.4 (Windows 10), Board: "Arduino Mini, ATmega328P"

Archiving built core (caching) in: C:\Users\UMME-K~1\AppData\Local\Temp\arduino_cache_566019\core\core_arduino_avr_mini_cpu_atmega328_3f323efdab4276426e9d8710d5d73f64.a
Sketch uses 3932 bytes (13%) of program storage space. Maximum is 28672 bytes.
Global variables use 250 bytes (12%) of dynamic memory, leaving 1798 bytes for local variables. Maximum is 2048 bytes.
D:\Amna\arduino-1.8.4\hardware\tools\avr/bin/avrdude -CD:\Amna\arduino-1.8.4\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\UMME-K~1\AppData\Local\Temp\arduino_build_808790/buzzer.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "D:\Amna\arduino-1.8.4\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

An error occurred while uploading the sketch

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

What should I do?


texts:
I'm trying to connect my Arduino Uno with MySQL.

This is my code:

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

/* Setup for Ethernet Library */
byte mac_addr[] = { 0xC8, 0x0A, 0xA9, 0xAF, 0x83, 0x58 };
IPAddress server_addr(192,168,0,102);

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference
char user[] = "root";
char password[] = "fifa2005";
char INSERT_SQL[] = "INSERT INTO test_arduino.hello VALUES ('Hello from Arduino!', NULL)";

void setup() {
Ethernet.begin(mac_addr);
Serial.begin(115200);
delay(1000);
Serial.println("Connecting...");
if (my_conn.mysql_connect(server_addr, 3306, user, password))
delay(500);
else
Serial.println("Connection failed.");
}

void loop() {
}

I have the following database:

mysql> CREATE DATABASE test_arduino;
Query OK, 1 row affected (0.00 sec)
mysql> USE test_arduino;
Database changed
mysql> CREATE TABLE hello (source char(20), event_date timestamp);
Query OK, 0 rows affected (0.01 sec)

This is the output message:

Connecting... Connection failed.

I am not sure this is the right IP address: 192,168,0,102. I tried with the localhost IP address - 127.0.0.1, but nothing happened.


texts:
Hey There Arduino Coders. I am a relatively seasoned C/C++ programmer. However, I'm still new to the Arduino Game. I'm coming here today to ask you guys a direct question that I couldn't find a direct answer for on google... here it goes:

Is it possible,(also practical) to create my own arduino board? after creating a prototype with an arduino uno and various shields?

In other words. Is it possible to shrink the arduino(make a custom arduino), and all of its shields on to one board? It seems rather large to have to lug around all of those shields and such. CHEERS!


texts:
I am new with arduino and hardwares at all and I am having some problems in a project where I want to assemble the head tracker device from this project https://git.iem.at/DIY/MrHeadTracker/wikis/mrht-bno055 ... They use an Arduino pro mini for data processing (with a .ino sketch provided by them), an Arduino USB 2 Serial micro for connecting the pro mino to the pc, and a sensor BNO055 by Adafruit which provides orientation data. I am using the same hardwares instead of the USB converter that in my case is the ft232rl by FTDI. The step I am having problem is the one where I have to flash the HIDUINO firmware (they provide an .hex file) so I can use the whole thing as a MIDI device.

The point is that I just don't understand if I have to overwrite the pro mini's serial firmware or the usb converter's and how it's the correct way to do it, mainly because I can't find examples with the usb converter I have and every new reference I read makes me think of one possibility. In the first link they suggest reading the information in https://github.com/ddiakopoulos/hiduino/wiki which presents 2 methods: DFU method, that tells I need Atmel Flip software for Windows and ISP method, that I don't know if is my case because I can't find out if my ftdi board is an ISP programmer. I've read about it and in other references also, but I am still not sure about what I have to do.
I hope that someone can help! And sorry for the basic doubts...
Thanks!


texts: Uni-directional communication between NodeMCU and Arduino spits out garbage

texts:
I am sending data from ESP8266 (NodeMCU) to Arduino using serial and 9600 baud rate on both sides. Since it is uni-directional and from NodeMCU to Arduino, I am not using a voltage regulator and I have connected tx (Software Serial) of NodeMcu to Rx of Arduino. I've connected the usb of nodeMCU to my computer. I've done the same thing to power Arduino.

Here is some sample code on NodeMCU:

#define Arduino_RX 4 // D2
#define Arduino_TX 5 // D1
SoftwareSerial ArduinoSerial(Arduino_RX, Arduino_TX); // RX | TX

void setup() {
  Serial.begin(115200);
  ArduinoSerial.begin(9600);
  delay(10);

  // Connect to WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");
}

void loop()
{
    ArduinoSerial.println("hi");
    Serial.println("hi");
    delay(1);
}

Code on Arduino

#define ESP8266_RX   2
#define ESP8266_TX   3
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(ESP8266_RX, ESP8266_TX); // RX | TX

void setup() {
  // put your setup code here, to run once:
    Serial.begin(9600);     // communication with the host computer
    ESPserial.begin(9600);
    Serial.println("Ready");

}

void loop() {
  if ( ESPserial.available() )   {
    Serial.write( ESPserial.read() );
  }
}


texts: How would you add Arduino WiFi Module using I2C or serial interface?

texts:
I am new to Arduino prototyping. I bought an Arduino Automatic Smart Plant Watering Kit 2.0 thinking it was a shield to use with my Arduino Uno WIFI Rev 2.  However, it turns out to be a specially designed Arduino board with all of the components integrated together.

While the system works as designed, my goal is to stream the data to IBM Watson Studio, or some other third-party SaaS.

I welcome feedback to understand how it might be possible to integrate the ESP8266 WIFI module using either the I2C or Serial interface. Here is the sample code: https://www.elecrow.com/download/watering_kit.zip I used a Raspberry Pi to get access to the data and use it in a web/mobile application but I'd like to eliminate this element, if possible.


texts: checking if user is opening root entry point of the IP address on esp8266 webserver

texts:
I am trying to open load a webpage from ESP8266 that displays temperature and humidity of my room if I only type root URL:192.168.1.89

GET / HTTP/1.1
Host: 192.168.1.89
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Safari/602.1.50
Accept-Language: en-us
DNT: 1
Accept-Encoding: gzip, deflate

to do that in my esp8266 sketch I am trying this logic:

bool readRequest(WiFiClient& client) {
  bool currentLineIsBlank = true;
  while (client.connected()) {
    if (client.available()) {
      char c = client.read();
      if (c == "GET / HTTP/1.1"){
        Serial.println("Got root");
        client.println(handleRoot()); // where handle root contains web page
      }
      else{
        Serial.println("Did not got root.");
      }
      if (c == '\n' && currentLineIsBlank) {

        return true;
      } else if (c == '\n') {
        currentLineIsBlank = true;
      } else if (c != '\r') {
        currentLineIsBlank = false;
      }
    }
  }
  return false;
}

but the condition to check if it met GET / HTTP/1.1 never validates.


texts:
I am trying to send gps location data every 3 seconds to mqtt server if it's updated but my device shows weird stack errors and resets. What i am missing?

I am using tinygps++ and pubsubclient as libraries.

LOOP:

void loop() {
  if (WiFi.status() != WL_CONNECTED)
  {
    connectWifi();
  }
  if (WiFi.status() == WL_CONNECTED && !client.connected())
  {
    mqtt_connect();
  }
  client.loop();

  if (WiFi.status() == WL_CONNECTED && client.connected())
  {
    long now = millis();
    if (ss.available() > 0)
    {
      if (now - lastMsg > 3000) {
        lastMsg = now;
        gps.encode(ss.read());
        display.setTextSize(1);
        display.setTextColor(WHITE);
        display.setCursor(0, 0);
        display.println("Lat:" + String(gps.location.lat(), 6));
        display.setCursor(0, 10);
        display.println("Lng:" + String(gps.location.lng(), 6));
        Serial.print("Latitude  : ");
        Serial.println(gps.location.lat(), 5);
        Serial.print("Longitude : ");
        Serial.println(gps.location.lng(), 4);
        if (gps.location.isUpdated())
        {
          String pos = String(gps.location.lat(), 6) + ";" + String(gps.location.lng(), 6);
          client.publish(mqtt_output, pos.c_str());
          display.setCursor(0, 50);
          display.println("Data Sent");
          m_alert();
        }
        display.setCursor(0, 30);
        display.println("Satellites: " + gps.satellites.value());
        display.setCursor(0, 40);
        display.println("HDOP: " + gps.hdop.value());
        display.display();
      }
    }
  }
}

connectWifi :

void connectWifi() {
  Serial.println('\n');

  WiFi.begin(ssid, password);             // Connect to the network
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  int i = 0;
  while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(1000);
    Serial.print("*"); Serial.print(' ');
  }
  w_alert();
  Serial.println('\n');
  Serial.println("Connection established!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());
}

mqtt_connect :

void mqtt_connect() {
  Serial.print(F("MQTT Connecting..."));

  char* clientId = "app";
  while (!client.connected()) {
    mqttConnectAttempt = millis();
    if (client.connect(clientId, mqtt_user, mqtt_pass)) {
      s_alert();
      Serial.println(F("connected"));
      String ready = "Connection Success!\r\n";
      client.publish(mqtt_output, ready.c_str());
      client.subscribe(mqtt_output);
    }
    else {
      Serial.print(F("Failure, rc="));
      Serial.print(client.state());
      Serial.println(F("Connecting Again in "));
      Serial.print(MQTT_PERIOD + " Seconds");
      delay(MQTT_PERIOD);
    }
  }
}


texts:
I currently have a 50,000 mAH USB power bank powering my Arduino Uno and micro servomotor. Unfortunately, my power bank has an automatic shutoff and shuts off after 2 hrs of runtime (I need 16 hrs for my project). I can restart the power bank by hitting the on button and it will run just fine for another 1-2 hrs at which point it will shut off. In one instance, the power bank ran for the desired 16 hrs straight hours. I believe that my arduino/servo are very close to the current threshold of the bank which could explain some of the variability I am seeing in terms of turn-off time. Would hooking up a resistor in the circuit do the trick and if so where?

Not quite sure about the brand of power bank (just one I found off Ebay). I believe the arduino uno and servo consume about 60 mA for power.


texts: Arduino : distance measurement between fixed points

texts:
I am creating a moving robot which needs to know its exact position on the map(known before, start point also known). My ideas were :

GPS : this is not accurate enough for me, does not work indoors
Acc + GYRO + Compass(Magnetometer): MPU-9150 : from that values I could compute the position but as small errors are continuously added after a while it becomes very inaccurate

Finally my idea is to put some fixed points into the area and robot can periodically check where they are and compute its position accurate.

Although I did some googlin' I could not find any appropriate sensor pair to do this. My idea is:

one(more if no other option) sensor on robot covering 360 degrees
few fixed points which sends a signal; each different one - let's say : I am the point one. I am the point two etc.
sensor on a robot is receiving those signals and give me some meaningful value e.g. time from which I can compute the distance from each of the fixed point.
10+ meters maximum range is fine for me
must be cheap (less than 30$ for all)

Questions:

Do you have any idea of such sensor pair ?
Or other solution which would fit to my needs?

Bonus:
* The best would be if the fixed points were passive and just reflected the signal sends from robot - but I have no clue if such a thing exist :-)

Thanks in advance for any answers/comments.


texts: Precise rotation (steering direction to a given angle) on obstacle avoidance robot

texts:
Forgive my lack of knowledge of some robotic related terms, but the way my two wheel drive robot steers is simply by having each wheel move at different speeds; for left, for example, the left wheel moves while the right one stays stationary for a given delay of time and vice versa.
but I want to make my obstacle detection a little more sophisticated with the following logic:

As the robot moves, scan the environment using an ultrasonic sensor(60 degrees to left and 60 degrees to the right) and using a simple max finding algorithm find the optimal angle i.e. angle at which the ultrasonic reading was highest. and then I want to find a way, using the same system of vehicle rotation if possible, turn to that specific angle proceed to move forward and scan simultaneously.

what I aim to achieve in the end is smoother obstacle avoidance as compared to the most common stop when close to obstacle -> turn left or right -> move and loop


texts: Looking for an accurate and fast updating range sensor

texts:
I need to purchase a distance sensor that will be fixed in place and used to determine distance to the top of a fairly fast moving piston along the axial direction in line with the sensor. The top of the piston can be covered in whatever material works best for sensor accuracy, and the entire apparatus can operate in the dark if needed. Distance will range from 50mm to 500mm. Position measurement must have an accuracy range below 1.5mm. Update rate must be 1000hz or greater (i.e. update every 1ms or faster).
I see there are many options for me at high cost, but I'm limiting my budget to $500 and below for the next few days while I research more. This does not mean I won't spend whatever is needed however. As of now I've seen nothing acceptable for under that price, but it's hard to tell as many companies won't publish prices for these types of sensors.
I'm happy to explain more about the implementation if needed, but until then ...
Many thanks for taking the time to help! John


texts: Improper functioning of Node mcu when connected to source other than PC

texts:
I connected EM18 rfid reader to NodeMCU to read rfid card data. It showed card number very quickly and consistently till it was connected to my PC's USB. But when I connected it to 5v power source (mobile phone charger) then it didnt read cards well i.e. sometimes it read and sometime dosent.
Thants very strange.
Grounds might not be the issue as EM18 is powered from NodeMCU and NodeMCU ultimately connected to source(mobile phone charger)

Code is given below :

int count = 0;
char input[12];
boolean flag = 0;

void setup()
{
   pinMode(LED_BUILTIN, OUTPUT);
   // begin serial port with baud rate 9600bps
   Serial.begin(9600);
}

void loop()
{
   if(Serial.available())
   {
      count = 0;
      // Read 12 characters and store them in input array
      while(Serial.available() && count < 12)
      {
         input[count] = Serial.read();
         count++;
         delay(5);
      }
      // turn the LED on (HIGH is the voltage level)
      digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  }
}


texts:
I have an OLED with this 7 pin pinout:

I want to use an existing code i found that makes use of U8Glib.
But in the example, use uses 4 pins to control the OLED via I2C.
This is the pinout he uses:

Is it possible to control my OLED via 4 pins and use U8Glib to simplify my project by making use of the example code i found?

EDIT: Here is also a picture of the back of the OLED PCB that mentions how to use IIC but i do not understand it!


texts: Using digital rotary encoders for HID input using the Joystick library

texts:
I have been working on a small switch panel for flight sims, but I wanted to use  the CYT1100 Digital Rotary encoders to move instruments in-game. I have the code  set up to press a certain joystick button for each pulse. The code seems to work fine, but I might have some issues with hardware.

Components:

Arduino Micro
CYT1100 Digital Rotary Encoders
Acer Aspire E5 (Windows 10)

I get serial monitor outputs when I move the board, but the rotary encoders aren't plugged in. The values are around 2 to -2 but don't change depending on the encoders. The joystick buttons are getting almost randomly pressed with no certain pattern. I was wondering if anyone has had issues like this in the past or if I'm missing something.

Here's my code:

#include <Joystick.h>

#define outputA 2
#define outputB 3

int counter = 0;
int aState;
int aLastState;

void setup() {
  Joystick.begin();
  pinMode(2, INPUT);
  pinMode(3, INPUT);
}

void loop() {
  aState = digitalRead(outputA);
  if (aState != aLastState) {
    if (digitalRead(outputB) != aState) {      // Clockwise
      Joystick.pressButton(1);
      delay(10);
      Joystick.releaseButton(1);
      counter ++;
    } else {                   // Counterclockwise
      Joystick.pressButton(2);
      delay(10);
      Joystick.releaseButton(2);
      counter --;
    }
    Serial.print("Counter:  ");
    Serial.println(counter);
  }
  aLastState = aState;
}


texts: Circuit with a tip120 works with a Led but, don't with a vibrator motor

texts:
I have 2 Arduino Nano's. One with RF transmitter and the other with an RF receiver of 433 MHz and both have two 3v vibration motors. I want one Arduino to send a string to the other Arduino to let him know which vibrator he needs to vibrate. The connection works, when the Arduino with the transmitter sends a message, the other Arduino gets the message and sets pin 2 (the pin for the vibrator via a tip120) HIGH. But the vibrator does not vibrate. When I change the vibrator with a led it works, the led goes on and off. So why does the led work but the vibrator motor not?

I use the VirtualWire library for the RF modules.

Here is the code and I also provided a summary:

Summary: This is the receiver Arduino code. message_received is the string variable where the message is stored and in the loop, that message is to check what it contains. And then the led goes off and on.

#include <VirtualWire.h>

byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = 255; // the size of the message

String message_received;

String message_go_on = "GO_ON";
String message_go_off = "GO_OF";

void setup() {
  Serial.begin(9600);
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  Serial.println("RECEIVER MONITOR");
}

void loop() {
  // put your main code here, to run repeatedly:
  if (vw_get_message(message, &messageLength)){ // Non-blocking
    Serial.print("Incoming message: ");
    for (int i = 0; i < messageLength; i++){
      Serial.write(message[i]);
      message_received += (char)message[i];
    }
    Serial.println();
  }
  if(message_received == message_go_on){
    digitalWrite(2, HIGH);
  }
  if(message_received == message_go_off){
    digitalWrite(2, LOW);
  }
  message_received = "";
}

Summary: This is the code of the transmitter. I have 2 messages that I want to send every 200 milliseconds. The send method is for the transmitter and it needs a char array so I change the string to a char[] with a toCharArray() method.

#include <VirtualWire.h>

String message_go_on = "GO_ON";
String message_go_off = "GO_OF";

char buf1[VW_MAX_MESSAGE_LEN];
char buf2[VW_MAX_MESSAGE_LEN];

void setup() {
  Serial.begin(9600);
  vw_setup(2000); // Bits per sec

  message_go_on.toCharArray(buf1,VW_MAX_MESSAGE_LEN);
  message_go_off.toCharArray(buf2,VW_MAX_MESSAGE_LEN);
  Serial.println("TRNASMITTER MONITOR");
}

void loop() {
  send(buf1);
  delay(200);
  send(buf2);
  delay(200);
}

void send (char *message)
{
  vw_send((uint8_t *)message, strlen(message));
  vw_wait_tx(); // Wait until the whole message is gone
}

The circuit of the receiver Arduino:

I think the vibrator might be undersupplied but why would the led work?

Thanks for the help!


texts:
Hi I am a beginner in Arduino Uno. I wanted to store a value of 77880 in EEPROM and fetch it later. I made the code as follows to check my logic(I am using Arduino Uno) :
#include <EEPROM.h>
int addr = 0;
byte value;
void setup() {
  // put your setup code here, to run once:
  int val = 77880;
  EEPROM.write(addr, val);
  Serial.begin(57600);
}

void loop() {
  // put your main code here, to run repeatedly:
  value = EEPROM.read(addr);

  Serial.print(addr);
  Serial.print("\t");
  Serial.print(value);
  Serial.println();
  delay(1000);
}

but I am not getting the value of 77880 when I read the EEPROM address. instead I am getting a value of  56 in my serial output. Can anybody pls explain how should I implement the same?


texts:
In my house, I have a low voltage AC signal (0-10V) that is proportional to the amount of current that is drawn at any moment (or as it is presented: kW) (europe, 50Hz). Presently, it is just shown as a dial in my kitchen, of course I would to log this. I want to rectify and integrate this singnal over an appropriate time span (maybe on minute) As far as I can see, I basically have two ways of doing this:

The pure arduino approach: Using a voltage divider to get it down to 0-5 V (after rectification) (and maybe throw in a zener diode as an extra protection) Then using an adc in the arduino and measure the voltage directly. The problem I foresee with this approach is that I will need a pretty high sampling rate to make sure I get the peak values. If I managed to sample at exactly the same frequency as my mains,I could just calibrate the measured value (unless I managed to hit the cross overs) but I do not think that would be feasible So I think I need to maybe sample on approx 500 Hz and pick out the highest value from each 1/50 second.
Using an opamp, a few resistors and a capasitor to set up an analog integration circuit, then use the arduino to read out and reset that at appropriate times. Setting up the integration circuit is no problem for me, but I need some feedback on the reset circuit. I have been looking around a bit, but I have not found any standard way to reset an integrator circuit, it seems like the idea is that it should be integrating for as long as it is running.. As far as I can see, as long as it running on <= 5V, I could use an input on the arduino to drain it? - I would then need to make the dimensions such that the low current the arduino input draws will allow the integrator to be reset fast enough.

Any comments? Have I overlooked something? is there a third approach that I have not been thinking about? Is the 1st approach easier that what I think?


texts: How to turn two LED's on and off with one button?

texts: I was wondering how to write a code that would do this, WITHOUT using IF and ELSE: when the button is pressed, one LED is on and the other one is off, but when the button is not pressed, the LED that was on turns off and the other one turns on.


texts: Voltage divider arduino 5v and Ethernet board 3.3

texts:
I have an Arduino Nano 5v module and I just received an Ethernet Interface Board - ENC28J60 that runs at 3.3v. (https://www.sparkfun.com/products/765)

Might sound a dumb question but I will power the Ethernet board from a Voltage regulator that can deliver 3.3v but then I have to connect via SPI to my Arduino controller. I guess I can't connect my Arduino pins directly to the Ethernet board right? because HIGH in the pin will be 5v instead of 3.3v.

  Do I need to add a Voltage divider for those pins connections? And in case I need to what resistance values are the right ones to use?

Thanks


texts: How can I have code in a project that won't compile for Arduino?

texts:
I want to test the algorithms in my code without needing to send it to an actual Arduino board. I figured I could lay out my project like:

project/
    core.cpp      # core algorithms
    core.h        # header for core.cpp
    project.ino   # Arduino setup() loop() calling into core
    pc-main.cpp   # main(argv) calling into core

However, when I do this, the Arduino IDE wants to compile pc-main.cpp, which won't work since it uses stdio and all that. What can I do instead?

Is there a way to hide a file from the build, other than changing the extension which would inconvenience other editors and compilers? Is there a different standard approach to this kind of problem?

What I've thought of:

I could put pc-main.cpp in another directory and have the build for it refer to the files in the Arduino project directory, but that seems awkward and I'd like a more elegant solution.
I could symlink the core.* files into the Arduino project directory from elsewhere, but that would also be inelegant, and inconvenience Windows users should one want to compile the project.
I could put an #ifdef around the contents of pc-main.cpp, but I haven't found a suitable #define to check for, other than board-specific ones.

I don't want a solution which requires extra steps for each build; the whole point of trying to do this is fast and easy development.

I would also prefer one which does not bring in a whole additional build system, testing framework, or IDE; for example, I found arduino_ci and PlatformIO while researching this question. I'll switch to looking at such options if there isn't a good solution to the problem as I've stated it here.

[My question is arguably the same as Project structure to build for PC and Arduino at a high level, but the question and answer there are broad and about organizing modules and not how to make the build actually work.]


texts:
i have a need to use 3 buttons a a simple option/variable selector at sketch start up ...

Pretty much at startup , script must wait for button press ( one of 3 ) , when button is pressed , use that buttons predefined string value as a variable for the loop script further down .. if wanting to change the "variable" then a reboot is required ..

i know how to digital read in the buttons , but not sure how to

1) wait for one of the buttons to be pressed to then jump to main loop
2) Associate a "string" variable to each button

thinking about it i suppose a If/Else loop will be required for the Input 'wait" and then just if the digital input (button) is pushed then continue .. am i correct ?

Ideas or better way to do it ?

Thx
Greg


texts:
I have a TIP 120 to 229 NON 60V 5A transistor

I'm trying to use it to switch an electro magnet. Using the blink example to test it out:

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

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

pin 13 is connected to the base and I'm trying to powering the magnet with a 12V DC adapter. I'm not sure if the transistor is before or after the magnet, but I'm not sure how that would make a difference.

I'm not great with diagrams but something like this (the power source might be the other way around:

simulate this circuit – Schematic created using CircuitLab

I've tried switching between the collector and the emitter. In one instance the magnet is always active and in one instance it's always passive. What could be wrong?

The cords running of the table in the bottom is just a bit of extra wiring.


texts:
I have an ATmega328P Arduino and am trying to make the LED blink using assembly without any additional includes. The goal is to have it blink for 1 second on, then 1 second off, however, it blinks incredibly quickly and is barely perceptible. Am I doing something incorrectly?

; DDRB       = 0x04
; PORTB      = 0x05
; TCCROB     = 0x25
; TCNT0      = 0x26
; 0b00000000 = OFF
; 0b00100000 = ON

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


texts: A friend of mine bought two of these Bluetooth shields here. I have been trying to get the two Arduinos connected to each other through Bluetooth. I could not get it working myself but I found some code online here that I tried. The shields connect to each other (the lights on both turn red) but the I can't send data between them. Does anyone have any code that may works with these shields?


texts: Transmitting multiple values to the arduino, and Interpreting them with minimum delay

texts:
I am building an underwater robot, which can move Up/Down, Forward/Reverse, controlled by a Joystick.
The situation is like this :
USB Joystick is connected to a PC, PC is connected to an Arduino via tether cable (Ethernet), and motors of the robot are connected to the arduino.
The joystick I am using is having 2 sticks, and I have decided to use 1 stick to control the UP-DOWN movement (Actually, I'm using only 1 axis of that stick for this.) and the 2nd stick to control the LEFT-RIGHT movement.
My question is, Whenever the user manipulates both the sticks simultaneously (To achieve diagonal motion, for example), The joystick will send 2 signals, one after the other, one for each stick. Keeping in mind the limited receiver buffer size of the arduino, how do I program the arduino, such that it can understand the difference between linear motion signal and diagonal motion signal?
I am highly motivated to program this on my own. I just need an Intuition for this.
A thought came to my mind is, to use the following strategy:
For my Up-down stick value, I add a character such as 'U', followed by the integer joystick value. For E.g. I send "U4" to go up at speed 4. With some twitching, I can even send down signal with the same preceding character U.
Similarly, for Forward/Backward, I send "F3" to go fwd/bkwd at speed 3. And for diagonal, I send something like "T5" to go diagonally at speed 5.
My concern with this is, I will transmit 2 characters from the PC to Arduino. Will the arduino be able to read such 2 characters, interpret them and act accordingly, without the noticeable lag? Or is there any other better way?
This also makes me wonder, how commercial robots (such as Commercial Drones) handle such situations?
The movements the robot will make needs to be quick. There should not be "visible" lag, That is, the user should not feel that the Robot is responding after a couple of seconds.


texts: Failed to read DHT22 sensor using Arduino Uno

texts:
why do I end up with the display "Failed to read from DHT sensor!" in the serial monitor in most cases when I run the code given below?? In case I reduce the delay to 1000ms the reading shows 0.00 for both temperature and humidity which, as well, is pretty much false......Any help would be highly appreciated...

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN 2     // what pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
// NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
// might need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold.  It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
// Arduino Due that runs at 84mhz a value of 30 works.
// Example to initialize DHT sensor for Arduino Due:
//DHT dht(DHTPIN, DHTTYPE, 30);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(f, h);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hi);
  Serial.println(" *F");
}


texts: Open Parent Class as Child Class (SD Fat Library)

texts:
I'm currently using the SDFat library and am passing a global FatFile

I if have a function that requires an SdFile type and I know that a given instance of FatFile is a valid SdFile what is the best way to reopen FatFile F as SdFile J?

Right now I'm doing:

SdFile ActiveFile;  //Global Active File
...
void SDRun (FatFile &RunFat)
{
  SdFile RunRoot;
  RunRoot.open("/", O_READ);
  ActiveFile.close();
  ActiveFile.open(&RunRoot,RunFat.dirIndex(),O_READ);
  ....

However, this only works when RunFat is in the root directory.


texts: i2c slave write to ARM powered device master

texts:
I want to communicate to an ARM microprocessor via I2C protocol (Multitech mDot, which uses Mbed platform). I successfully receive data from it (and got it displayed on Arduino's serial monitor), but when I want to send data from the Arduino I don't receive nothing on the other end. This is my sketch:

#include <DHT.h>
#include <Wire.h>

// Sensor temperatura, humedad DHT11 (test).
#define DHTPIN 10
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// Comunicacion i2c con nodo lora. 7bitaddress 010 1001 (r/w)
#define SLAVE_ADDRESS 0x29

// Variables globales de sensores
float h;
float t;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveEvent);
  dht.begin();
  Serial.begin(9600);
}

void loop() {
  delay(5000);
  h = dht.readHumidity();
  t = dht.readTemperature();

  // Comprobamos si ha habido algún error en la lectura
  if (isnan(h) || isnan(t)) {
    Serial.println("Error obteniendo los datos del sensor DHT11");
    return;
  }

  Serial.print("Humedad: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperatura: ");
  Serial.print(t);
  Serial.println(" *C ");

  Wire.onReceive(receiveEvent);
}

// Total de bytes del arreglo de datos a transmitir: 28 bytes.
void receiveEvent(int howMany) {
  Serial.print("Mensaje recibido por i2c desde MDOT LoRa Node: ");
  while (Wire.available() > 0) {
    Serial.print(char(Wire.read()));
  }
  Serial.println();
  char enviar = "Cacatua";
  Wire.write(enviar);
  return;
}

I wanted to know if this schematic is correct and if the wire write as it is written is performed. If so, I will need to see what is wrong with the code on my ARM device.


texts: Existence of a non blocking and task yield framework for Arduino programming

texts:
I've been playing around with Arduino and understand that the standard runtime provides a single thread essentially.

I was wondering if it is possible to write a thin layer (library) that allows one to write code that is non blocking and one where each task yields control manually which allows the master loop to implement some form of timesharing.

I'd appreciate any:

Comments on existing frameworks that can allow me to write my programs this way
Any comments on how hard implementing anything of this order of magnitude would be.


texts: How to rotate two or more steppers simultaneously by giving ARRAY of angles?

texts:
The following is the code that I am trying but the problem is steppers rotate one after each other. However, I want to rotate steppers simultaneously.
This code for two stepper motors.

int pulse=3;

int direc=4;

int pulse1=5;

int direc1=6;

int i,j,k;

float angle[5][3]={{360,360,3},{7,8,9},{11,12,13},{14,15,16},{17,18,19}};

float steps;

void motor1(){

  for(k = 0; k<=4; k++){

    Serial.println(angle[k][0]);

    steps = (1600*angle[k][0])/360;

    Serial.println(steps);

    for(j = 0; j<=steps;j++){

      digitalWrite(3,HIGH);

      delayMicroseconds(100);

      digitalWrite(3,LOW);

      delayMicroseconds(100);
        }

}

}

void motor2(){

  for(k = 0; k<=4; k++){

    Serial.println(angle[k][1]);

    steps = (1600*angle[k][1])/360;

    Serial.println(steps);

    for(j = 0; j<=steps;j++){

      digitalWrite(5,HIGH);

      delayMicroseconds(100);

      digitalWrite(5,LOW);

      delayMicroseconds(100);

        }

}

}

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

  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
}

void loop(){
    motor1();

    motor2();

   //while(1);
}


texts: Unable to upload sketches to Sparkfun Redboard

texts:
I have two sparkfun redboards. Neither board will allow a sketch to be uploaded from the Arduino IDE.

I plug in a board and it powers on. In the Arduino software I select Tools->Port->COM4 (the only option) and Tools->Board->Arduino/Genuino Uno. Then compile and upload the Blink example. I get the following errors:

Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\andy\AppData\Local\Temp\arduino_build_463875/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x5f

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I understand that this is a fairly generic error indicating failure to communicate with the board, but I don't know what to do about it. I have various Arduino Unos and Arduino Megas and can upload sketches to them without a problem. Since it seems unlikely that both redboards are faulty (different batch numbers), I suspect a software problem relating to the ftdi-based serial comms used by the redboards.

I'm using Windows 10 x64 with Arduino IDE v1.8.5 and FTDI drivers v2.12.28.0 x64 (all latest). I've also tried another windows 10 machine and a different usb cable, with the same results.

I'd appreciate any suggestions.

Update

I've tried using an ftdi cable to connect to the boards on pins 0 and 1. I get the same error message.

I've also tried running avrdude manually and varying some of the parameters. No luck with that either.


texts: How to Serial read two consecutive chars sent by computer to Arduino?

texts:
My program reads the input and plays the appropriate note for 500 milliseconds. If I type in 'a', tone(8, 440, 500) will be called. I now want to add different note lengths so that in the future, I can play songs by sending code to Arduino. I was thinking that if 'a' is typed in, the program checks the next character. If it's a 1, it's a whole note. If it's a 2, it's a half note. My code doesn't work. What is wrong with it?

    if(Serial.available()>0){
    char character=Serial.read();
    if(character=='a'){
    char leng=Serial.read();
    if(leng=='1'){
    tone(8, 440, 1000);
    delay(1000);
    }
    else if(leng=='2'){
    tone(8, 440, 500);
    delay(500);
    }

    }
    }


texts: NeoPixel library performance: Adafruit vs. FastLED

texts:
I'm new to these addressable LED things – I just received a 149-LED WS2812B strip today, and I'm experimenting with various approaches. Adafruit's own tutorial says the FastLED library is faster than their Adafruit_NeoPixel library, so I wanted to test their performance.

I'm running this code on a Nano clone:

// Adafruit
#include <Adafruit_NeoPixel.h>
// FastLED
#include <FastLED.h>
// Common
#define NUM_LEDS 149
#define DATA_PIN 6

// Adafruit initialization
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, DATA_PIN, NEO_GRB + NEO_KHZ800);
const uint32_t adaBlack = strip.Color(0, 0, 0);
const uint32_t adaWhite = strip.Color(255, 255, 255);

// FastLED initialization
CRGB leds[NUM_LEDS];

void setup() {
  // Common
  delay(2000);

  // Adafruit setup
  strip.begin();

  // FastLED setup
  FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);

  // Common
  Serial.begin(57600);
}

void loop() {
  unsigned int adafruitMillis = adafruitLoop();
  unsigned int fastLedMillis = fastLedLoop();
  // Yes, this is ugly -- but it works every time
  Serial.print(adafruitMillis);
  Serial.print(",");
  Serial.println(fastLedMillis);
}

unsigned int adafruitLoop()
{
  long unsigned startMillis = millis();
  for (int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed++) {
    strip.setPixelColor(whiteLed, adaWhite);
    strip.show();
    strip.setPixelColor(whiteLed, adaBlack);
  }
  return (unsigned int) millis() - startMillis;
}

unsigned int fastLedLoop()
{
  long unsigned startMillis = millis();
  for(int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed++) {
    leds[whiteLed] = CRGB::White;
    FastLED.show();
    leds[whiteLed] = CRGB::Black;
  }
  return (unsigned int) millis() - startMillis;
}

The results are totally disastrous for FastLED (shown in red):

Am I doing something wrong, or is FastLED winning on features, rather than on speed?

For the record, I did check whether the performance hit comes from setting the pixel values or from sending the data – FastLED is faster at setting the pixel values than Adafruit's library, but that doesn't matter because setting two pixel values takes 3 ms or less for the entire strip, regardless of the library. Sending the data to the strip takes most of the time, and that's where FastLED lags behind big time (900 ms compared to Adafruit's 200 ms).


texts:
I have written a code but I am facing a problem in pseudo-code that I am not able to change this code, so can anyone help me in translating the Arduino IDE program code to pseudo-code?

#define BLYNK_PRINT Serial
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include<DHT.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
char auth[] = "py0oKurvtk_Rv2GGkKtghpKqlxLQug8F";
char ssid[] = "Hostal1";
char pass[] = "shakajutt7867";
DHT dht(D4, DHT11);
SimpleTimer timer;
int Relay = D5;
int PIR = D3;
void sendSensor()
{
  float humi = dht.readHumidity();
  float temp = dht.readTemperature();
  int value = digitalRead(PIR);
  if (value == 1)
  {
  digitalWrite(Relay, HIGH);
  Serial.print("Detected");
  Serial.print('\n');
  lcd.setCursor(0,0);
  lcd.print("PIR = Detected");
  lcd.setCursor(0,1);
  lcd.print("T: ");
  lcd.print(temp);
  lcd.setCursor(7,1);
  lcd.print(" H:");
  lcd.print(humi);

  }
  else if (value== 0)
  {
    digitalWrite(Relay, LOW);
    Serial.print("Not Detected");
    Serial.print('\n');
  lcd.setCursor(0,0);
  lcd.print("PIR = Not Det");
  lcd.setCursor(0,1);
  lcd.print("T:");
  lcd.print(temp);
  lcd.setCursor(7,1);
  lcd.print(" H:");
  lcd.print(humi);

  }
  Blynk.virtualWrite(V7, value);
  Blynk.virtualWrite(V5, humi);
  Blynk.virtualWrite(V6, temp);
  delay(1500);
}
void setup()
{
  pinMode(Relay, OUTPUT);
  pinMode(PIR, INPUT);
  digitalWrite(Relay,LOW);
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  dht.begin();
  lcd.begin(16,2);
  lcd.init();
  lcd.clear();
  lcd.backlight();
  lcd.setCursor(0,0);
  timer.setInterval(1000L, sendSensor);
}
void loop()
{

  Blynk.run();
  timer.run();
}


texts: Creating formatted String (including floats) in Arduino-compatible C++

texts:
I'm using a Mega2560 and a generic SSD1306 OLED display with the Adafruit_SSD1306 (and by extension, Adafruit_gfx) library.

I need to print a bunch of float values (ranging between 30.0 and 99.9) to the display with exactly one decimal place of precision. The catch is, the Adafruit library doesn't have a printf() method, only one that takes a single ready-to-print string.

Here's an (obviously non-Arduino) Java-like example of what I'm trying to accomplish:

String foo = String.format("%.1f, %.1f\%", temp1, hum1);
// "display" is my instance of Adafruit_SSD1306
display.print(foo);

So... how can I do something similar in Arduino-compatible C(++)?

Note: for this specific program, I have (relatively speaking) RAM to burn, so I really don't care if whatever library I use to generate formatted Strings is particularly efficient (as long as it isn't leaking). If it wants to use 4k of RAM and 80k of flash to format a 20-character String, so be it.


texts: Problems with serial communication from Arduino to ESP8266

texts:
I've been trying to get an Arduino and ESP8266 to communicate with each other over serial. The ESP8266 uses the Serial class for communications, while the Arduino uses SoftwareSerial.

The problem is that when I try to send data from the Arduino to the ESP8266,  only the first character of the string sent gets received by the ESP8266. For example, if I send a string "leather", the ESP8266 only receives an 'l'. Both devices are operating at 38400 baud, although I have tried 9600 baud with similar results (apparently SoftwareSerial is more reliable at lower baud rates).

Here is the relevant code that's running on both devices:

Arduino code:

#include <stdlib.h>
#include <SoftwareSerial.h>

#define COMMAND_TILT                'c'
#define SOFTWARE_SERIAL_BAUD_RATE   38400
#define ESP_RX                      8
#define ESP_TX                      9

SoftwareSerial esp(ESP_RX, ESP_TX);

void setup()
{
    ...
    esp.begin(SOFTWARE_SERIAL_BAUD_RATE);
    ...
}

void loop()
{
   if (esp.available() > 0) {
        String data;
        while (esp.available() > 0) {
            data += (char) esp.read();
        }

        char command = data.charAt(0);
        data.remove(0, 1);
        int value = data.toInt();
        char buf[STR_BUF_LEN];

        switch (command) {
             case COMMAND_TILT:
                 ...
                 sprintf(buf, "%c%d", COMMAND_TILT, value);
                 esp.write(buf);
                 break;
             ...
        }
    }

    delay(100);
}

...

ESP8266 code:

#define SERIAL_BAUD_RATE 38400

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

void loop()
{
    ...

    if (Serial.available() > 0) {
        String data;
        while (Serial.available() > 0) {
            data += (char) Serial.read();
        }

        char command = data.charAt(0);
        data.remove(0, 1);

        // problem: now, data.c_str() is blank when it should contain an integer in string format

        ...

        delay(100);
    }
}

...

If it helps to know, I'm running an MQTT client on the ESP8266 and controlling some steppers and relays on the Arduino.


texts: Differences between Arduino IDE versions

texts:
I run Arduino IDE on both my Mac and under Raspbian on a Raspberry Pi, both running the latest version of OS.

The Raspberry Pi has Arduino 2:1.0.5+dfsg2-4.1 and I am running the latest 1.8.4 on macOS.
Debian is always somewhat behind the latest software, and this has not concerned me before, as I have never had issues before. (I know I could download the latest ARM32 build or compile from source, but this would probably generate a lot of dependencies.)

I have recently run into a couple of problems.
Compiling a script which has #include <SdFat.h> generates an error, although the library is present in ~/sketchbook/libraries/SdFat/src/SdFat.h. This does not seem to be an issue on macOS.

I was also trying to program an Atmega using a Uno as ISP as in "Using an Arduino as an AVR ISP". I have done this in the past, but the instructions and the Arduino program seem to have changed; there is no longer "Upload Using Programmer" menu, but suggests the "Burn Bootloader" command. Does this upload both the Bootloader and Sketch?


texts:
I am currently writing a program that reads an output voltage from a capacitive moisture sensor and depending on the moisture content, it will water some plants accordingly. I would like to make it so that a user can change the condition in real time because different plants will require different amounts of water. This will give a little more freedom on how much water the user would prefer for their plant. This is the code I have so far:

int solenoidPin = 4; //connected to Digital 4
int moisturePin = A0; //connected to Analog A0

void setup() {
  Serial.begin(9600);
  pinMode(solenoidPin, OUTPUT);
}
void loop() {
  int val;
  moisture = analogRead(moisturePin); //connect sensor to Analog A0
  Serial.println(val); //print the value to serial port
  delay(1000); //wait 1 second for next reading

  if (moisture <= 350) //if moisture is less than reading 350 {
  digitalWrite(solenoidPin, HIGH); //switch solenoid ON
  delay(600000) //water for ten minutes
  digitalWrite(solenoidPin, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin, LOW); //switch solenoid OFF
  }
}

I am aware that there is a touch screen shield for the Arduino and I could possibly allow the user to interact what is going on. However, I'm just asking if it's possible to change the if (moisture <= 350) while the code is running and perhaps allowing the user to change that value. If so, then how? Could I use a touch screen shield or another shield that allows a user to change the condition?