texts: Battery Solution for ESP8266 and HC-SR04

texts:
I'm working on a project that includes an ESP8266 (requires 3.3v input (250 mA peak)) and a HC-SR04 (requires 5v 20 mA peak). I'm making it battery/solar powered.

I'm trying to keep costs down as well as make a system that works reliably and has good longevity.

I'll be waking the device every 15 minutes and keeping it in deep sleep at the other times.

Originally I was going to use a battery source over 6v, like a 6 cell AA rechargeable battery pack, a 10v or so solar panel, and a breadboard type voltage regulator that conveniently provides 3.3v and 5v on the same board. This seems to waste a decent amount of power though.

Right now I'm looking into using a 2 AA rechargeable NiMH batteries, a 5v solar panel, a 3.3v step up voltage booster, and a 5v step up voltage booster. 5v step up voltage boosters are everywhere and cheap because of their uses for portable cell phone chargers. 3.3v step up voltage boosters on the other hand are more expensive and harder to find.

Looking for any advice or affirmation that I'm on the right path. Thanks!


texts: Power down NRF24 to conserve battery life using MOSFET

texts:
I'm using a Pro-Micro to send messages using NRF24 module from a remote location, using batteries (later on, will be recharged using solar panel).
To conserve power, Pro-Micro wakes up every 30 minutes, sends its data. My goal is to power up NRF24 module only when needed, in order to conserve power as much as possible.
For that I tried 3 ways:

Using a Relay to cut off 5V input to the NRF24 module.

Using a MOSFET FQP30N06 , connected to GND of NRF24 module.

Using NRF24's powerDown() function reduce consumption.

These are the current draw results:
a) During sleep, power consumption of Pro-Micro only is 3.4 mA ( due to LED remains ON ).
b) Pro-Micro + NRF24 module, both normal operation ~70mA.
c) Using a relay + entering Pro-Micro to Sleep mode: 6mA.
d) Using powerDown() + entering Pro-Micro to Sleep mode: 30mA.
e) Using a MOSFET + entering Pro-Micro to Sleep mode: 180mA. (yes, MOSFET turns off power to NRF24 ).
Questions:
** I have to say that my first go was for using a MOSFET, but I was amazed by the result! What is the reason for that? Can it be the when MOSFET in its OFF state consumes so much power ?
** I would like to hear from other's experience for better ways to do such.
Guy


texts: Why does my LED turn off automatically after about 18 seconds on its own?

texts:
I am using the Arduino Due and I am programming it with Atmel Studio 6.2. I have had a HUGE learning curve using this IDE and the Atmel ASF. Nothing is straightforward as it is in the Arduino IDE. Nonetheless, I want to toggle an LED on and off with a simple interrupt on a pull-up configured tactile button. This is my code:

#include <asf.h>
#include "pio.h"

// Define the LED pins
#define BLUE_LED2 PIO_PC28 // Arduino Due pin 3
#define BLUE_LED3 PIO_PC26 // Arduino Due pin 4
#define BLUE_LED4 PIO_PC25 // Arduino Due pin 5
#define BLUE_LED5 PIO_PC24 // Arduino Due pin 6
#define BLUE_LED6 PIO_PC23 // Arduino Due pin 7

// Define the button pins
#define BUTTON_1 PIO_PC22
#define BUTTON_2 PIO_PC21

// Define function prototype for button interrupt
void button_press_handler(uint32_t, uint32_t);
void toggle_LED(uint32_t);

int main (void)
{
    /* Initialize the SAM system. */
    sysclk_init();

    // Initialize input/out
    ioport_init();
    pmc_enable_periph_clk(ID_PIOC);
    pmc_enable_periph_clk(ID_PIOB);

    // Set LED pins as outputs and set there default values (off)
    pio_set_output(PIOC, BLUE_LED2, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED3, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED4, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED5, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED6, LOW, DISABLE, ENABLE);

    // Set button pins as pull-up inputs
    pio_set_input(PIOC, BUTTON_1, PIO_PULLUP);
    pio_set_input(PIOC, BUTTON_2, PIO_PULLUP);

    // Configure button input pin interrupt mode and handler (Falling Edge)
    pio_handler_set(PIOC, ID_PIOC, BUTTON_1,  PIO_IT_RISE_EDGE, button_press_handler);
    pio_handler_set(PIOC, ID_PIOC, BUTTON_2,  PIO_IT_RISE_EDGE, button_press_handler);

    // Enable the interrupts
    pio_enable_interrupt(PIOC, BUTTON_1);
    pio_enable_interrupt(PIOC, BUTTON_2);
    NVIC_EnableIRQ(PIOC_IRQn);

    while(1){
         // Doing stuff in here...
    }
}

Then this is my interrupt routine:

// Interrupt handler for button press
void button_press_handler(uint32_t a, uint32_t b)
{
    // Turn the LED's on or off
    toggle_LED(BLUE_LED2);
    toggle_LED(BLUE_LED3);
    toggle_LED(BLUE_LED4);
    toggle_LED(BLUE_LED5);
    toggle_LED(BLUE_LED6);
}

// Function to toggle LED on/off
void toggle_LED(uint32_t LED){

    if (pio_get(PIOC, PIO_TYPE_PIO_OUTPUT_0, LED))
    pio_clear(PIOC, LED);
    else
    pio_set(PIOC, LED);
}

Things work normal and as expected up until about 18 seconds in. After 18 seconds, the LED turns off if it is on. I tested this by setting LED 2 HIGH by default and removing the interrupt all together:

pio_set_output(PIOC, BLUE_LED2, HIGH, DISABLE, ENABLE);

In this case, the LED will stay on forever, but about every 18 seconds, the LED will flash off then back on once quickly. Why is this happening?


texts: How to connect 70 analog sensor to a single Arduino (Mega or Uno) device?

texts:
I was working on a project in which I need to collect soil moisture data for a farm. For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino. But, this is not possible as there are just 6 analog pins on Arduino Uno and 16 analog pins on Arduino Mega. I have restrictions on the number Arduino that I can use that is just one due to monetary constrains.
        The data would be collected at a delay of 5 seconds. The data gathered would be stored on SD card module which would be analyzed later.
      Any suggestion on how I can collect data from 70 analog sensors on a single Arduino would be highly appreciated. Are there any alternatives that I can use in place of Arduino? I heard that we could do something with AVR  atmega Microcontroller, am I correct? I don't know how to use Microcontroller; any useful resources will be highly appreciated. Thank You.


texts:
I connected 4x716 Coreless DC Motors on pin 13,12,11,10 and 1xGY-521 to  Arduino Pro Mini 328, 5v but speed of propellers is not enough to produce enough torque to lift the quad whereas when i connect then  directly to 3.3v LiPo battery the quad has lift but because of no flight control it moves randomly.

I checked the voltage of pin 13,12... they have output as 0.5-0.6v, I think this is the reason quad is not lifting.

I am using following code

// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

int p1 = 13;
int p2 = 12;
int p3 = 11;
int p4 = 10;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
    pinMode(p1, OUTPUT);
  pinMode(p2, OUTPUT);
  pinMode(p3, OUTPUT);
  pinMode(p4, OUTPUT);
  digitalWrite(p1, 0);
  analogWrite(p2, 0);
  analogWrite(p3, 0);
  analogWrite(p4, 0);

  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);

   digitalWrite(p1, HIGH);
  analogWrite(p2, 250);
  analogWrite(p3, 255);
  analogWrite(p4, 255);

  delay(333);
}


texts:
Kind of a fringe question here, but could not find anything concrete so figured I would throw it to this great community.
I have 2 DS80 flow meters (Hall Effect Sensor type flow meters - nothing special about them except they are bigger for 3" pipes), and they work fine, wired, code, etc and get decent readings and all that so no issues there.
During my bench prototyping, I noticed that sometimes, in spite of no "flow", I would detect "pulses" from the sensor. Because they are sitting on a workbench, with no pipes connected, I assume this is either:

Random transient voltage, maybe bleed from its neighbors in the wiring or what not
Maybe the magnet on one fin is parked at the sensor and vibration is causing it to bounce

The second one is what it is, but the first one feels like something I could iron out. The question is, should I have a cap/resistor/something on the data line from the sensor to smooth out readings? Because it is PWM I do not know what to put there that wouldn't interfere with the signal itself (if anything). Absolutely NOT critical, as I said it works fine under load and I do not need hyper-accurate readings. More of a "could I do this better" question.


texts: Arduino stops working after some receivings from RF

texts:
I made a sketch that receives an rgb code from a remote Arduino using nrf24l01 and while it works for the first receivings then it stops working. I placed a testing Serial.println in the loop to test if Arduino stops to work completely or it doesn't receive any other data. Finally, I understood that it continues to work but it doesnt receive more data. Bellow is my code:

#include <RF24Network.h>
#include <RF24Network_config.h>
#include <Sync.h>

#include  <TimerOne.h>
#include <SPI.h>
//#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(8,10);
RF24Network network(radio);
volatile int i=0;
volatile int d=0;     // Variable to use as a counter
volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero
int AC_pin= 4;    // Output to Opto Triac pin
int dim = 0;  // Dimming level (0-128)  0 = ON, 128 = OFF
int freqStep = 65;

struct payload_rgb
{
  unsigned int red;
  unsigned int green;
  unsigned int blue;
};
struct payload_lightuv
{
  unsigned int light;
  unsigned int uv;
};
RF24NetworkHeader header;
payload_rgb payloadrgb;
payload_lightuv payloadl;
void setup() {
  // put your setup code here, to run once:
  pinMode(AC_pin, OUTPUT);// Set AC Load pin as output
  pinMode(9, OUTPUT);// Set AC Load pin as output
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  attachInterrupt(0, zero_cross_detect, RISING);  // Choose the zero cross interrupt # from the table above
  Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
  Timer1.attachInterrupt(dim_check, freqStep);
  Serial.begin(115200);
  radio.begin();
  network.begin(90,01);
}

void loop() {
  network.update();
  while ( network.available() )
  {
    Serial.println("Rec");

    network.peek(header);
    if(header.type=='r'){
      network.read(header,&payloadrgb,sizeof(payloadrgb));
      analogWrite(6,payloadrgb.red);
      analogWrite(9,payloadrgb.green);
      analogWrite(5,payloadrgb.blue);
    }
    if(header.type=='l'){
      network.read(header,&payloadl,sizeof(payloadl));
      dim=payloadl.light;
    }
}
Serial.println("!"); //this is the test println
}
void zero_cross_detect() {
  zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
  i=0;
  digitalWrite(AC_pin, LOW);       // turn off TRIAC (and AC)
}
void dim_check() {
  if(zero_cross == true) {
    if(i>=dim) {
      digitalWrite(AC_pin, HIGH); // turn on light
      i=0;  // reset time step counter
      zero_cross = false; //reset zero cross detection
    }
    else {
      i++; // increment time step counter
    }
  }
}}

Additionally, this Arduino controls an ac dimmer. Bu I have not done it yet.
How can I fix the problem without removing any feature?


texts: How to use d0 and d1 pins of arduino uno (Others) as a digital output when I don't want to use Serial

texts:
I have searched this topic almost everywhere also got different results that couldn't satisfy me
My new project is a 4x4 LED cube
Of which
Will contain 4 Rows and each Row will contain 16 LEDs
So, I need to use all the digital pins 0-15 as digital output.
And other pins 16-20 for grounding.
But the problem is, this project needs d0 and d1 pin to be connected as a digital output pin. (Not Serial communication)
In some places I have seen that Experts saying

If you want to use Serial communication, then you can't use them.

You can't use it while your arduino is connected to PC.

You Can't do this ,as this may harm the device

You must turn off serial connection first.

OK, reading this, I got confused, I don't need to use any serial connection (console and others) in this LED cube project so I tried to turn off serial connection by not writing the code below.
Serial.begin(9600);

So, will that free those d0 and d1 pins as digital for me ? Or USB connection is also considered as a serial connection?
So, how can I do it? And will doing it really harm my board?


texts: Arduino/DuinOS vs Normal C/ARM Programming

texts:
I'm trying to understand the difference between programming Arduino hardware (Atel/ARM based) versus 'normal C-based ARM programming'.

My understanding is that the Arduino language is cross-compiled into C-compatible binary, and the Arduino EEPROM libraries are used to effectively 'flash' your Arduino code onto the Atel/ARM chip, which is running DuinOS. Your Arduino 'app' (software) can then take advantage of DuinOS utilities, such as scheduling, semaphores, events, critical sections, etc.

My understanding is that if I wanted to program an ARM chip myself from scratch, I would have to use something called an ISP programmer to 'flash' an embedded RTOS onto the chip first. Then, I would have to write C code, compile it, and again use the ISP programmer to deploy the compiled binary to the ARM chip, which is already setup to boot the RTOS when powered on.

I'm sure I'm mucking up a few things here, but this is my general understanding: can someone correct/clarify these things for me?


texts:
I have been using an Arduino Nano as a PWM controller for a heating element.

I am currently using D11 (PB3). I could change, although all pins with PWM are in use, and would require a re-write and re-wire.

This produces a signal at ~490Hz, but I would like to experiment with changing this to a higher frequesncy.

I gather it its possible to vary the frequency by changing the divisor from its default 64.

My sketch uses Uses http://playground.arduino.cc/Main/SevenSegmentLibrary and calls millis() - will changing PWM divisor impact on either of these?

NOTE I have read the setPwmFrequency documentation, but find "disrupts the normal operation" unhelpful - I am actually after some explanation of the concrete effect. I only use millis() to time button presses and flash a LED, which are not time critical

Please keep in mind that changing the PWM frequency changes the Atmega's timers and disrupts the normal operation of many functions that rely on time (delay(), millis(), Servo library).

I have been doing some further study. http://playground.arduino.cc/Code/PwmFrequency states  Changes on pins 3, 5, 6, or 11 may cause the delay() and millis() functions to stop working.

Other references say 3, 11 use timer 2 so do they affect millis() or not as other references claim timer 0 is used for these.


texts: Weird sound when modulating the pulse width on Arduino

texts:
I'm trying to generate a pulse width modulated sound using Arduino Nano.

But it generates the weird sound unlike my expectation.

Here's my code:

class Phasor
{
public:
    Phasor(const float frequency)
    :frequency(frequency)
    ,phase(1.0f)
    ,lastTimeMicros(0){};
    virtual ~Phasor(){};
    void setFrequency(const float frequency)
    {
        this->frequency = frequency;
    }
    float process()
    {
        const unsigned long currentTimeMicros = micros();
        if (phase == 1.0f) lastTimeMicros = currentTimeMicros;
        const unsigned long elapsedTimeMicros = currentTimeMicros - lastTimeMicros;
        const unsigned long cycleDurationMicros = static_cast<unsigned long>(1000.0f / frequency) * 1000;
        if (elapsedTimeMicros < cycleDurationMicros)
            phase = static_cast<float>(elapsedTimeMicros) / static_cast<float>(cycleDurationMicros);
        else
            phase = 1.0f;
        return phase;
    }
private:
    float frequency;
    float phase;
    unsigned long lastTimeMicros;
};

class PulseOsc
{
public:
    PulseOsc(const float frequency, const float pulseWidth)
    :phasor(frequency)
    ,pulseWidth(pulseWidth){};
    virtual ~PulseOsc(){};
    void setFrequency(const float frequency)
    {
        this->phasor.setFrequency(frequency);
    }
    void setPulseWidth(const float pulseWidth)
    {
        this->pulseWidth = pulseWidth;
    }
    float process()
    {
        const float phase = phasor.process();
        if (phase <= pulseWidth)
            return 1.0f;
        else
            return -1.0f;
    }
private:
    Phasor phasor;
    float pulseWidth;
};

Phasor *phasorLFO;
PulseOsc *pulseOsc;

void setup()
{
    Serial.begin(9600);
    pinMode(9, OUTPUT);
    phasorLFO = new Phasor(0.1f);
    pulseOsc = new PulseOsc(440.0f, 0.5f);
}

void loop()
{
    pulseOsc->setPulseWidth(phasorLFO->process());
    int outVal = LOW;
    if (pulseOsc->process() > 0.0f) outVal = HIGH;
    digitalWrite(9, outVal);
}

The resulting sound is very weird and glitchy.
It works fine when I fix the pulse width value. (without LFO)

What is wrong with my code?
How do I fix this? I would appreciate any advice.


texts: Conversion between boolean and int went wrong

texts:
I have a small problem with conversion from bool array to int. It is working fine until it comes to the 12th cycle of while. I don't know why but this is really weird.

I try to paste here a code where I am doing this conversion.

int* BoolToInt(bool* set) {
  int* ret = (int*)malloc(3*sizeof(int));
  int sum0 = 0;
  int sum1 = 0;
  int sum2 = 0;
  //bool test[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1};
  for(int m=0; m<24; m++) {
    if(m<8) {
      sum0 += (int)set[m] * (pow(2,m));
    }
    if(m>7 && m<16) {
      sum1 += (int)set[m] * (pow(2,(m-8)));
    }
    if(m>15 && m<24) {
      sum2 += (int)set[m] * (pow(2,(m-16)));
    }
  }
  ret[0] = sum0;
  ret[1] = sum1;
  ret[2] = sum2;
  Serial.print("\n ret[0] = ");
  Serial.print(ret[0]);
  Serial.print("\n ret[1] = ");
  Serial.print(ret[1]);
  Serial.print("\n ret[2] = ");
  Serial.print(ret[2]);
  return ret;
}

And this is where I am using this function:

void Fitness(bool** set) {
  int maX = 0;
  int index = 0;
  int* temp;
    for(int i=0; i<10; i++) {
    int* phenotype = BoolToInt(set[i]);
    _fitness[i] = 1000/((phenotype[0] - _colours[0])*(phenotype[0] - _colours[0]) + (phenotype[1] - _colours[1])*(phenotype[1] - _colours[1]) + (phenotype[2] - _colours[2])*(phenotype[2] - _colours[2]) + 1);
    Serial.print("\n phenotype[0] = ");
    Serial.print(phenotype[0]);
    Serial.print("\n phenotype[1] = ");
    Serial.print(phenotype[1]);
    Serial.print("\n phenotype[2] = ");
    Serial.print(phenotype[2]);
    free(phenotype);
  }
  for(int i=0;i<10;i++) {
    temp = BoolToInt(set[i]);
    if(_fitness[i]>maX) {
      maX = _fitness[i];
      index = i;
    }
  }
  setColorOnSecond(temp[index]);
  free(temp);
}

As seen in the Fitness function, I have some debugging prints to see if everything is fine. My main is in the while cycle. Everything is fine and "ret" from BoolToInt function is the same as "phenotype" in Fitness, which is a good thing and this is what I want. But then the 12th cycle comes and phenotype[1] gives me 1200 as int. And of course everything in ret[] is fine(0-255). Am I doing something wrong?

NOTE: bool* set in BoolToInt is 24 bool array (yes 3 numbers as you can see).

NOTE 2: every previous cycle before 12th cycle is good and the result are equal.


texts: Can I configure pairing for HC-05 and Arduino, and use the HC-05 without Arduino after?

texts:
I have a system that is outputting data via its serial, and I need to relay that data to my PC wireless-ly. If I were to setup an Arduino and HC-05 at the system's side to relay the data, that would mean I need to use two serial ports. I know this could be done with SoftwareSerial library. However, I would like to know if I could set up the pairing between master and slave with arduino, then unplug the HC-05 from the Arduino, and connect it directly to the system's serial output. Would this work?

Edit for clarification:

I do not want to use SoftwareSerial
I do not want to use an MCU during normal operations
I want the HC-05 to take in serial data from a system's serial, and transmit it via bluetooth to my PC
Only during pairing configuration, will I want use an MCU (Arduino) to set it up. I want to know if the comms will still work when I take out the Arduino and connect the system's serial data output to HC-05's Rx instead.

Is this possible?


texts: Why cannot I input arrays as digitalWrite arguments?

texts:
I am making my own "7 segment LED driver". I know there is a lot of examples on the internet, I just want to try my own. But I have a piece of code that does not work and I don't know why. Can somebody explain to me why it is not working?

When I put in this, it works:

digitalWrite(pins[0], one[0]);
digitalWrite(pins[1], one[1]);
digitalWrite(pins[2], one[2]);
digitalWrite(pins[3], one[3]);
digitalWrite(pins[4], one[4]);
digitalWrite(pins[5], one[5]);
digitalWrite(pins[6], one[6]);

So of course I tried using for():

for (byte i = 0; i >= 6; i++)
  {
    digitalWrite(pins[i], one[i]);
  }

And this does not work. But why? I think it should. Btw. pins is const byte array and one is const bool array.

Thanks in advance for any suggestions!


texts: NodeMCU Wi-Fi connection status sending to MySQL database

texts: I have a simple iot web app built with bootstrap, PHP, MySQL and some JavaScript/JQuery hosted on a server. I have several NodeMCUs (each having unique id) and I'm sending temperature data via HTTP GET requests which communicates with PHP API and inserts data in the MySQL database. All is working perfectly. Now I want to show the connection status of all NodeMCUs. If a NodeMCU is connected to my Wi-Fi then I want to show "Online" on my web app and if NodeMCU gets disconnected from Wi-Fi then "Offline" should be printed on web app. How can I achieve this?


texts: how to get serial data to wait until a certain length is reached

texts:
I have a code that loops through 2 different serial inputs on the arduino mega, and sends them to serial constantly:

int RFIDResetPin = 13;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  pinMode(RFIDResetPin, OUTPUT);
  digitalWrite(RFIDResetPin, HIGH);
}

void loop() {

  char tagString1[13];
  int index = 0;
  boolean reading1 = false;
  boolean reading2 = false;
  ///////////////////////////////////////
  //this reads from the reader installed
  //on serial1, which is pin 19
  //////////////////////////////////////
  while (Serial1.available() > 0) {

    int readByte1 = Serial1.read(); //read next available byte

    if (readByte1 == 2) reading1 = true;
    if (readByte1 == 3) reading1 = false;

    if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
      tagString1[index] = readByte1;
      index++;
    }
  }
  Serial.println(String("Reader 7: ") + tagString1); //the tag itself

delay(1);
  clearTag(tagString1); //Clear the char of all value
  resetReader(); //reset the RFID reader
  //////////////////////////////////////////////////
  // This bit reads from serial2, located on pin 17
  /////////////////////////////////////////////////
  while (Serial2.available() > 0) {

    int readByte2 = Serial2.read();

    if (readByte2 == 2) reading2 = true;
    if (readByte2 == 3) reading2 = false;

    if (reading2 && readByte2 != 2 && readByte2 != 10 && readByte2 != 13) {
      tagString1[index] = readByte2;
      index++;
    }
  }
  Serial.println(String("Reader 8: ") + tagString1);

  clearTag(tagString1);
  resetReader();
}

void resetReader() {
  ///////////////////////////////////
  //Reset the RFID reader to read again.
  ///////////////////////////////////
  digitalWrite(RFIDResetPin, LOW);
  digitalWrite(RFIDResetPin, HIGH);
  delay(150);
}

void clearTag(char one[]) {
  ///////////////////////////////////
  //clear the char array by filling with null – ASCII 0
  //Will think same tag has been read otherwise
  ///////////////////////////////////
  for (int i = 0; i < strlen(one); i++) {
    one[i] = 0;
  }
}

when not scanning anything, the serial monitor outputs this:

Reader 1:
Reader 2:
Reader 1:
Reader 2:

When I scan a tag, lets say on reader 1, I get this:

Reader 1: 000004f5
Reader 2:
Reader 1: 000004f5
Reader 2:

it is not possible to scan more than a single scanner at a time. Is it possible to get the first line to wait until a certain number of characters have been scanned (indicating a tag has been scanned), and then output to the serial monitor?After that initial run, the code will loop as I showed above. any help is appreciated.


texts:
I installed the MATLAB support package for arduino in my MATLAB r2013a today.
Now I plugged on my Arduino in my usb port.

And ran the command:

    a = arduino()

    Error: Undefined function or variable 'arduino'.

When I get:

    a = arduino('COM18')

    Undefined function 'arduino' for input arguments of type 'char'.

I have checked that this package has been installed.

It is grey.

Any help will be appreciated.

Thanks very much

Anupam.


texts: Beat 1 LED light is always on - should turn off

texts:
/**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 11;
const int keyPinR = 10;
int buttonState = LOW;
int buttonState2 = LOW;
int bpm = 120;
int rthm = 1;
/**************************************/
void setup()
{
  Serial.begin(9600);
   for(int thisPin = 1;thisPin <= ts;thisPin++)
   {
 pinMode(thisPin,OUTPUT); //initialize thisPin as an output
 pinMode(8, INPUT);

 pinMode(keyPin, INPUT);
 pinMode(keyPinR, INPUT);
 digitalWrite(keyPin, HIGH);
 digitalWrite(keyPinR, HIGH);
 }

}

/****************************************/
void loop()
{
 buttonState = digitalRead(keyPin);
 buttonState2 = digitalRead(keyPinR);
 if(buttonState==LOW){
 ts++;
  if(ts==6)
   {
    ts = 2;
   }
  }
 if(buttonState2==LOW){
  rthm++;
    Serial.println(rthm);
  if(rthm==5)
  rthm = 1;

  }
  for(int thisPin = 1;thisPin <= ts;thisPin++)
  {

  for(int r = 1; r<=rthm; r++){
   bpm = pulseIn(6, HIGH);
    digitalWrite(thisPin,HIGH);

    pinMode(13,OUTPUT);

    if(count == 1&&r==1)
    tone(13,1500,40);
    else if(r==1)
    tone(13,1000,40);
    else
    tone(13,500,40);
    delay((bpm-52)/rthm);

    digitalWrite(thisPin,LOW);
    pinMode(13,INPUT);

   }
    count++;
    if(count >ts)
    count = 1;
    }

   }

This is a metronome project. Each LED represents a beat. However, The LED for beat 1 is always on. It should turn off when it's on a different beat other than one. Is there anything wrong with the code?


texts: Is it possible to make an HTTP get request using AT Commands without knowing the IP address of the web server?

texts:
I have the following code that can read a web page using HTTP get but I can only do it because the website I am doing it to has a static IP address, but in my project I am just hosting it on a free service and IP changes rapidly. So is there a way to do the same with only the URL address?

#include <SoftwareSerial.h>

SoftwareSerial cell(2,3);  // Create a 'fake' serial port. Pin 2 is the Rx pin, pin 3 is the Tx pin. connect this to the GSM module

const String apn = "web2"; // access-point name for GPRS

const String ip = "212.26.27.181"; // IP address of server we're connecting to
const String host = "kfu.edu.sa"; // required in HTTP 1.1 - what's the name of the host at this IP address?
const String request = "GET /sites/Home HTTP/1.1";
const String useragent = "Mozilla/5.0"; // for our purposes the user agent doesn't matter - if I understand correctly it's helpful to use something generic the server will recognize

void setup()
{
  //Initialize serial ports for communication with computer
  Serial.begin(9600);

  Serial.println("Starting SM5100B Communication...");
  cell.begin(9600);

  waitTil("+SIND: 4"); // keep printing cell output til we get "+SIND: 4"
  Serial.println("Module ready");
}

void loop()
{
  Serial.println("Attaching GPRS...");
  cell.println("AT+CGATT=1");
  waitFor("OK");

  Serial.println("Setting up PDP Context...");
  cell.println("AT+CGDCONT=1,\"IP\",\""+apn+"\"");
  waitFor("OK");

  Serial.println("Activating PDP Context...");
  cell.println("AT+CGACT=1,1");
  waitFor("OK");

  Serial.println("Configuring TCP connection to TCP Server...");
  cell.println("AT+SDATACONF=1,\"TCP\",\""+ip+"\",80");
  waitFor("OK");

  Serial.println("Starting TCP Connection...");
  cell.println("AT+SDATASTART=1,1");
  waitFor("OK");

  delay(5000); // wait for the socket to connect


texts:
Presumably, one powers an Arduino board with car batteries for long-term operation away from the power grid.

How can this be done, and what are the most (1) economic, and (2) reliable ways to do this? Specifically, do any additional risks to short the board with an extraneous discharge exist?


texts:
I have a 8 relay module that should use not more than 20 mA per relay.
Altough when measuring it asks around 70.
If I use 6 relays, that would be more than an Arduino Mega can give.
(I already lost 1 arduino here.)

How this is possible..?


texts: Arduino acts odd when disconnected from computer

texts:
I'm building an self-navigating robot with an arduino, an ultrasonic sensor, and two DC motors. I'm currently within the process of coding the robot but I've discovered I have an unusual problem; whenever I run the project via the USB cable operations run fine, however once I take the cable out and run the system on batteries alone performance diminishes.

I have checked the code thoroughly, however I don't understand how this could be an issue that's coding related. I also (as part of the testing) built a basic program which only operated the motors, and was able to run this via USB and via batteries alone with no difference in performance.

So what possible reasons could there be for a drop in performance? I have included a link to a youtube video I had taken of it earlier below to maybe give a better understanding of how performance diminishes:

https://youtu.be/Tp5LtOKBKHw

(Also it could be important to note if I take the cable out while motors are currently moving performance stays at where it should be)

Thanks!


texts: Detect how long a push button is being pressed?

texts:
I would like to detect how long the state on/off is going on for. Is there a way to do that? I would like to do that for two reasons:

I would be able to make a very simple toggle button. (I know about the other way with the old value and new value).
I can make the button being pressed for a long time be like a return button.

Anyone got any ideas?


texts:
println() function is being used to send AT commands to GSM module.
sim800l.println("AT+CLTS=1");
  delay(3000);
  sim800l.println("AT+COPS=2");
  delay(3000);
  sim800l.println("AT+COPS=0,0");
  delay(3000);

But problem is the output -
AT+CLTS=1

OK
AT+COP

The command AT+COP did not print fully? Why?
Minimal Reproducable Example -
#include <SoftwareSerial.h>    //Library required for serial communication
char MYDATA[18];
SoftwareSerial sim800l(3, 2); // RX,TX for Arduino and for the module it's TXD RXD, they should be inverted
void setup() {
  Serial.begin(9600); //Start the serial interface on 9600
  sim800l.begin(9600);
  delay(100);
  // AT command to set sim800l to SMS mode
  sim800l.println("AT+CMGF=1");
  //Serialcom();
  delay(100);
  // Set module to send SMS data to serial out upon receipt
  sim800l.println("AT+CNMI=2,2,0,0,0");
  delay(100);
  sim800l.println("AT+CLTS=1");
  delay(3000);
  sim800l.println("AT+COPS=2");
  delay(3000);
  sim800l.println("AT+COPS=0,0");
  delay(3000);
   sim800l.println("AT+CCLK?");
  Serial.find("+CCLK: \"");
  Serial.readBytesUntil('\+', MYDATA, 17);

}

void loop() {
 Serial.print(MYDATA);
}


texts: PWM using timer3 for servo control won't generate any output

texts:
I'm making a program for a small robot arm controlled by four servos.
Problem: I need for PWM outputs, timer1 has three so i need to use timer3 for the last one

The main program and the timer1 outputs work great, the robot arm is functional. My problem is in the initialization of the PWM's. The PWM for timer1 is set to phase-correct, 64 pre-scaling and using WGM1[0-3] to 1010 so that i can use ICR1 as the top value, leaving OCR1[0-2] for counting up so output is on OCR[0-2].

According to the ATMEGA 2560 data book I should be able to initialize an identical PWM with timer3 with just one output in just the same way, but it just won't give me any output at all on OC3A.

Any help is greatly appreciated! :)

PS this is for a class project, so no servo libraries, and no major changes to the program (the current code is already approved by my professor, also the due date is in 24 hours so i don't have the time. Yes I know that sounds like trouble, but the project is technically done, I'd just really really like to get a full range of motion on my little Plexiglas robot)

PWM.c:

// INITIALIZE PHASE CORRECT PWM ------------------------------------------------------------------------------
void initPWM()
{
    DDRB |= (1<<DDB7);      // Output pin 5 OC3A
    DDRB |= (1<<DDB5);      // Output pin 11 OC1A
    DDRB |= (1<<DDB6);      // Output pin 12 OC1B
    DDRB |= (1<<DDB7);      // Output pin 13 OC1C

    // Initialize TIMER1 for OC1A, OC1B, OC1C:
    TCCR1A |= (1<<COM1A1)|(1<<COM1B1)|(1<<COM1C1)|(1<<WGM11);     // Clear OCnA on compare match (non inverting mode), Phase correct ICRn top Mode
    TCCR1B |= (1<<WGM13)|(1<<CS11)|(1<<CS10);                     // Phase correct ICRn top Mode, Pre-scaling 64 for 50Hz signal
    // Initialize TIMER3 for OC3A
    TCCR3A |= (1<<COM3A1)|(1<<WGM31);                            // Clear OCnA on compare match (non inverting mode), Phase correct ICRn top Mode
    TCCR3B |= (1<<WGM33)|(1<<CS31)|(1<<CS30);                     // Phase correct ICRn top Mode, Pre-scaling 64 for 50Hz signal

    // TIMER1 Top and bottom value:
    ICR1 = 5000;
    TCNT1 = 0;
    // TIMER3 Top and bottom value:
    ICR3 = 5000;
    TCNT3 = 0;

    // Start PWM in OCR = 200 (mid value for servo)
    OCR3A = 200;
    OCR1A = 200;
    OCR1B = 200;
    OCR1C = 200;

}


texts:
I am fairly new to Java, but with a rather complicated question.

We are looking at reading some bytes coming in from an Arduino. The Arduino sends bytes in the form:

 Serial.print(Voltage1);
 Serial.print(voltage2);

Since these voltages are numbers of the format "1.62", two digits after the decimal point, the Arduino sends 8 bytes, 4 for each voltage.

Previously in a MATLAB test we managed that by making the inputbuffer=8, and then splitting the bytes by doing something of the sort A=buffer(1:4) B=buffer(5:8), and as such we could plot or read the signals from the Arduino.

Is there a way to achieve this in Java? At the moment we are creating an input stream, and we tried to limit that to a buffer of the correct size, but we do not get anything even close to the expected. Most of the time our input from inputstream.read() gives us negatives, but not even something that we can understand or work with.

I hope this is well explained, and I really wish someone knows how to deal with this problem.


texts: Can you use python to control an RGB matrix with Arduino Mega?

texts: I want to use python to control a RGB Matrix with an Arduino Mega, is it possible? How do I use Adafruit library with python? My plan is to create IOS app to control the matrix via Bluetooth.


texts: Choosing rangefinder for obstacle-avoiding

texts:
I am looking to buy a range finder module for an obstacle avoidance robot.
Currently, two good options based on available libraries and compatibility with Arduino and rPI are HC-SR04 and parallax ping.

In terms of form factor these seem the same. The only difference I can tell is 4 pins vs 3 pins. Also the price, with parallax being more than x4 the price. As I would rather not buy something cheaper which will need replacing, is anyone aware of further differences, that will make the parallax a better option?

both need 5V
both have max range of 3-4m
Sensor angle HC- 15 degrees, parallax cant find..


texts:
I made this circuit:

The part with the DC motor is from this tutorial: https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v32/experiment-12-driving-a-motor ( I only use another resistor, with 220 OHM)

As you can see, I also have a TMP36 sensor attached. What I would like to do is this:
When the temperature is 25 degrees or more, the motor should turn on.

I have this code:

//TMP36 Pin Variables
int sensorPin = 0; //the analog pin the TMP36's Vout (sense) pin is connected to
                        //the resolution is 10 mV / degree centigrade with a
                        //500 mV offset to allow for negative temperatures

/*
 * setup() - this function runs once when you turn your Arduino on
 * We initialize the serial connection with the computer
 */
void setup()
{
  Serial.begin(9600);  //Start the serial connection with the computer
                       //to view the result open the serial monitor
}

void loop()                     // run over and over again
{
 //getting the voltage reading from the temperature sensor
 int reading = analogRead(sensorPin);

 // converting that reading to voltage, for 3.3v arduino use 3.3
 float voltage = reading * 5.0;
 voltage /= 1024.0;

 // print out the voltage
 Serial.print(voltage); Serial.println(" volts");

 // now print out the temperature
 float temperatureC = (voltage - 0.5) * 100 ;  //converting from 10 mv per degree wit 500 mV offset
                                               //to degrees ((voltage - 500mV) times 100)
 Serial.print(temperatureC); Serial.println(" degrees C");

 if(temperatureC >= 25){
  analogWrite(9, 250);
 }

 delay(1000);                                     //waiting a second
}

But I get this result:

0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.75 volts
25.20 degrees C <------
0.87 volts
36.91 degrees C
0.66 volts
16.41 degrees C
0.78 volts
27.64 degrees C
0.77 volts
26.66 degrees C
0.84 volts
34.47 degrees C

The point where the sensor measures > 25 degrees, the motor turns on but the circuit gets "poluted" and the temp sensor starts to send all kinds of strange values.

How do I solve this?
Thanks in advance!

I got it to work in with the following: http:// i.stack.imgur.com/4GFPH.png


texts: SPI communication with Arduino and PGA411-Q1 resolver sensor

texts:
I have been trying to implement SPI communication between an Arduino board and a PGA411-Q1 resolver sensor board. I have set up the Arduino SPI settings as indicated on the resolver sensor's datasheet (http://www.ti.com/lit/an/slaa688/slaa688.pdf) - 8MHz sclock, MSB first and SPIMode1.

The communication is done by sending and receiving 32 bits both to and from the Arduino. The bits are distributed as follows.

Outgoing 32bit data frame by Arduino to the sensor:

O-5 bits: Arduino's CRC for data
6-7 bits: Always zero
8-23 bits: Data
24-31 bits: Register address

Incoming 32bit data frame by the sensor to the Arduino:

O-5 bits: Sensor's CRC for data
6-7 bits: SPI communication status
8-23 bits: Data
24-31 bits: Register address

Also, there is mandatory to send and receive a CRC6 code from both the board and Arduino and I have implemented it as well. (I will not be checking the CRC code received by the Arduino board. I will check it later. But I am already sending the CRC code needed by the sensor board).

This is the code written by me:

NOTE: The crc_cal function outputs the crc code from Arduino to the sensor along with the two 'always zero' bits.

#include <SPI.h>
unsigned int crc_cal (unsigned long datin);

 const int ncs = 10;
 unsigned char crc_char = 0x3F;

 void setup() {

  // initalize the chip select pin:
  pinMode(ncs, OUTPUT);
  pinMode(FAULTRES,OUTPUT);
  pinMode(NRESET,OUTPUT);

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

  //NRESET must go from LOW to HIGH
  digitalWrite(NRESET,LOW);
  digitalWrite(NRESET,HIGH);

  //wait at least 5ms to complete diagnostics tests
  delay(10);

  //FAULTRES LOW
  digitalWrite(FAULTRES,LOW);

  // start the SPI library:
  SPI.begin();

 // give the sensor time to set up:
  delay(100);

   }

void loop() {

SPI.beginTransaction(SPISettings(6400000, MSBFIRST, SPI_MODE1));

digitalWrite(ncs, LOW);

byte temp_3 = SPI.transfer(0x41);

byte temp_2 = SPI.transfer(0x0F);

byte temp_1 = SPI.transfer(0x0F);

byte temp_0 = SPI.transfer(crc_char);

digitalWrite(ncs, HIGH);

SPI.endTransaction();

unsigned int angle_raw = 0;
angle_raw = temp_2;
angle_raw = angle_raw << 8;
angle_raw = angle_raw | temp_1;
angle_raw &= 0x3FF;
Serial.println(angle_raw);

int crc = crc_cal(0x410F0F00);
unsigned char crc_char = crc;
crc_char = crc_char & 0x3F;
 delay(100);

 }

     /* CRC6 calculation - optimized for PGA411 */
 unsigned int crc_cal (unsigned long datin)
 {
 unsigned int byte_idx, bit_idx, crc= (0x3F << 2);
 /* byte by byte starting from most significant (3-2-1) */
 for (byte_idx = 3; byte_idx >= 1; byte_idx--)
 {
 /* XOR-in new byte from left to right */
 crc ^= ((datin >> (byte_idx<<3)) & 0x000000FF);
 /* bit by bit for each byte */
 for(bit_idx = 0; bit_idx < 8; bit_idx++)
 {
 crc = crc << 1 ^ (crc & 0x80 ? (0x5B << 2) : 0);
 }
 }
 return(crc >> 2 & 0x3F); /*restore two bit offset */

 }

I have used the code provided in the PGA411-Q1's datasheet (http://www.ti.com/lit/an/slaa688/slaa688.pdf) and it works fine when I check it manually. Some examples for input data frames and their CRC codes can be found in the section 7.5.4 of the datasheet found here http://www.ti.com/lit/ds/symlink/pga411-q1.pdf

As you may notice from the code I am sending the register address which I want data from in the first 8 bits of SPI.transfer. The read address of that register is 0x41.

Next, I'm sending two garbage values as data because this is a read-only register.

Finally, I'm sending the CRC code calculated by the crc_cal function.

All I'm receiving in the serial monitor are zeros and I can't figure out what went wrong. I would appreciate some insight into this.


texts: Arduino uno, 2x parallax continous servos (BOE), wifi shield power draw

texts:
I am unable to properly connect those things together with batteries:

Arduino Uno
Parallax continuous servo
Arduino wifi shield

5xAA batteries are connected through power jack to arduino which I assumed would power both arduino and the wifi shield and then I have 1 9 volt battery to power 2 servo motors.

With this setup it seems like I can only get to run 1 servo at a time.

Here is a picture how it looks like: http://imgur.com/0jtbPHT

I'm really desperate for any advice/guidance when it comes to powering this thing.


texts:
I am trying to make I2C Communication between NodeMCU and arduino Uno boards. However it is not working properly. It makes communication for once time when i uploaded code.
Master Device Code(NodeMCU 1.0)
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <Wire.h>

HTTPClient client;

StaticJsonDocument <200> doc;

const char* ssid = "MY_SSID";
const char* pass = "MY_PASSWORD";

void setup() {
  Serial.begin(9600);
  Wire.begin(D1,D2);
  WiFi.begin(ssid,pass);
  while(WiFi.status() != WL_CONNECTED) {;}
}

void loop() {

  const char* cd = getCode();
  if(cd==nullptr) {
    Serial.println("Problem Occurred.");
    delay(10000);
    return;
  }
  //Bad code is starting...
  //Basically, sending 24 bytes of data for a Wire Transmission

  int n = strlen(cd);
  int rem = n%24; //remainder
  int quo = (n-rem)/24; //quotient

  while(quo!=0) {
    char sel[24];

    for(int i =0;i<24;i++) {
      sel[i] = cd[((((n-rem)/24)-quo)*24)+i];
    }

    Wire.beginTransmission(8);
    Wire.write(sel);
    Wire.endTransmission();
    quo-=1;
  }

  char sel[rem];

  for(int i =0;i<rem;i++) {
    sel[i] = cd[n-rem+i];
  }

  if(rem>0) {
     Wire.beginTransmission(8);
     Wire.write(sel);
     Wire.endTransmission();
  }
  //Bad code finished!

  //this is also not working.
  Wire.requestFrom(8,3);

  while(Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }

  delay(15000);
}

//get code from server.
const char* getCode() {
  client.begin("http://...");

  int res = client.GET();

  if(res<0) {
    return 0;
  }

  String root = client.getString();
  deserializeJson(doc,root);
  const char* code = doc["Liste"][0]["code"];
  return code;
}

Slave Device Code(Arduino Uno)
#include <Wire.h>

void setup() {
  Serial.begin(9600);
  Wire.begin(8);
  Wire.onReceive(received);
  Wire.onRequest(requested);
}

void loop() {delay(200);}

void received(int bytes) {

  while (Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }

}

void requested() {
  Wire.write("abc");
}

Circuit:
D1-SDA
D2-SCL
GND-GND


texts:
Can I turn Yun to ad hoc mode?

How to?

As the image above I can see the Ad-Hoc model in that drop down list. But only WEP for its security.


texts: How can I add PWM to my BLDC code using port manipulation?

texts:
I have the following code, which currently uses 6 output pins (pins 8 - 13) from the Arduino to my inverter circuit, which controls a BLDC motor. The code is fine and it works, however I want to add PWM using port manipulation and not analogWrite, as this is not fast enough for this application.

I know for example I could write OCR1B = 200, which sets the duty cycle of pin 10 to 200 and replaces the analogWrite function, but I do not know where to put this in my code. Also, do I need 3 PWM pins as the commutation of a BLDC motor is done in 6 steps in order to do 1 full revolution, or do I only need 1 PWM pin?

void setup() {
  pinMode(A0, INPUT); // sensor inputs
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
  DDRB  |= B00111111; // Sets D8, D9, D10, D11, D12 and D13 as OUTPUT
  PORTB &= B11000000; // D8 to D13 LOW
}

void loop() {
  switch (PINC) {
    case 3:
      PORTB |= _BV(PB3); // set pin 11 high
      PORTB |= _BV(PB5); // set pin 13 high
      PORTB &= ~_BV(PB0); //set low
      PORTB &= ~_BV(PB1); //set low
      PORTB &= ~_BV(PB4); //set low
      PORTB &= ~_BV(PB2); //set low
      break;
    case 2:
      PORTB |= _BV(PB3); // set pin 11 high
      PORTB |= _BV(PB4); // set pin 12 high
      PORTB &= ~_BV(PB5); //set low
      PORTB &= ~_BV(PB2); //set low
      PORTB &= ~_BV(PB1); //set low
      PORTB &= ~_BV(PB0); //set low
      break;
    case 6:
      PORTB |= _BV(PB2); // set pin 10 high
      PORTB |= _BV(PB4); // set pin 12 high
      PORTB &= ~_BV(PB0); //set low
      PORTB &= ~_BV(PB1); //set low
      PORTB &= ~_BV(PB3); //set low
      PORTB &= ~_BV(PB5); //set low
      break;
    case 4:
      PORTB |= _BV(PB2); // set pin 10 high
      PORTB |= _BV(PB0); // set pin 8 high
      PORTB &= ~_BV(PB1); //set low
      PORTB &= ~_BV(PB5); //set low
      PORTB &= ~_BV(PD3); //set low
      PORTB &= ~_BV(PD4); //set low
      break;
    case 5:
      PORTB |= _BV(PB1); // set pin 9 high
      PORTB |= _BV(PB0); // set pin 8 high
      PORTB &= ~_BV(PB2); //set low
      PORTB &= ~_BV(PB4); //set low
      PORTB &= ~_BV(PB5); //set low
      PORTB &= ~_BV(PD4); //set low
      break;
    case 1:
      PORTB |= _BV(PB1); // set pin 9 high
      PORTB |= _BV(PB5); // set pin 13 high
      PORTB &= ~_BV(PB0); //set low
      PORTB &= ~_BV(PB4); //set low
      PORTB &= ~_BV(PB3); //set low
      PORTB &= ~_BV(PB2); //set low
      break;
  }
}


texts:
I have an Arduino Mega with an MaxBotix (MB7066) sonar attached, the sonar has the ability to send serial data with it's reading. It uses a asynchronous RS232 format, except the voltages are 0-Vcc. The output should be a capital "R" (ASCII), followed by four digits(ASCII) and a carriage return (ASCII 13). The baud rate is 9600, 8 bits, no parity with one stop bit.
What I get from the device is as follows: (sonarSerial.read() while sonarSerial.available())

43
192
6
6
179
89
30
0

What do I have to get to the information? Or is my sensor just retuning garbage?
Please see the code below:

#include <SoftwareSerial.h>

#define pin1 3
#define pin2 5 //pwm
#define pin3 6 //analog
#define pin4 10 //RX for sonar, TX for arduino
#define pin5 11 //TX for sonar, RX for arduino

SoftwareSerial sonarPort(pin5,pin4);

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

   pinMode(pin4, OUTPUT);
   pinMode(pin5, INPUT);
   sonarPort.begin(9600);
}

void loop(){
  digitalWrite(pin1, HIGH);

  digitalWrite(pin4, LOW);
  digitalWrite(pin4, HIGH);
  delayMicroseconds(20);
  digitalWrite(pin4, LOW);

  long pulse = pulseIn(pin2, HIGH)/58;
  Serial.print("PM Result: ");
  Serial.println(pulse);

  String buffer = "";
  sonarPort.listen();
  while(sonarPort.available() > 0){
      int inByte = sonarPort.read();
      buffer += inByte; buffer += " ";
      if(!sonarPort.available()){
          Serial.print("Serial result: ");
          Serial.println(buffer);
      }
  }
  delay(500);
}


texts: SD Card Library interferes with Adafruit

texts:
Im currently working on a datalogger that uses oled i2c displays and current sensors. Both of them uses adafruit libraries. To write the data, im using arduino's sd library, but somehow, the sd library interferes with my i2c components that they won't work while sd card functions work. adding any sort of code from the sd library would completely make the i2c components malfunction. To test this, i tried to view 2 different text in 2 different i2c displays.
Here's the current code where the i2c components work :
#include <Adafruit_SSD1306.h>
#include "SdFat.h"

#define OLED_RESET 4
Adafruit_SSD1306 Display1(OLED_RESET);
Adafruit_SSD1306 Display2(OLED_RESET);

int i, j;

void setup()   {

  //Serial.begin(9600);

  Display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  Display1.clearDisplay();
  Display1.display();

  Display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);
  Display2.clearDisplay();
  Display2.display();

}

void loop() {

  Display1.setTextSize(1);
  Display1.setTextColor(WHITE, BLACK);
  Display1.setCursor(0, 0 );
  Display1.println("Hello");
  Display1.display();
  Display1.clearDisplay();

  Display2.setTextSize(1);
  Display2.setTextColor(WHITE, BLACK);
  Display2.setCursor(0, 0);
  Display2.println("There");
  Display2.display();
  Display2.clearDisplay();

}

And here is the code where the components doesn't work
#include <Adafruit_SSD1306.h>
#include "SdFat.h"

#define OLED_RESET 4
Adafruit_SSD1306 Display1(OLED_RESET);
Adafruit_SSD1306 Display2(OLED_RESET);
SdFat SD;

int i, j;

void setup()   {

  //Serial.begin(9600);

  Display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  Display1.clearDisplay();
  Display1.display();

  Display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);
  Display2.clearDisplay();
  Display2.display();

}

void loop() {

  Display1.setTextSize(1);
  Display1.setTextColor(WHITE, BLACK);
  Display1.setCursor(0, 0 );
  Display1.println("Hello");
  Display1.display();
  Display1.clearDisplay();

  Display2.setTextSize(1);
  Display2.setTextColor(WHITE, BLACK);
  Display2.setCursor(0, 0);
  Display2.println("There");
  Display2.display();
  Display2.clearDisplay();

}

Adding any sort of code that involves the sd card library like adding files or declaring the SD command itself would make the i2c components unusable, does anyone know how to fix this?


texts:
I want to use ESP32 to control and use a dimmer for 6 LED panels in my bedroom. The specification of each panel is mentioned in the diagram. Although in the diagram it shows ONLY 1 MOSFET and 1 LED Panel but in reality there are 6 LED Panels therefore I am guessing that each of the 6 LED Panel will need a separate MOSFET.

I would like to know:

What MOSFET (Part number or model number, company name,  etc) should I use for the above LED panel connected with ESP32 (I guess voltage of ESP32 is 3.3 v) ?
Will each LED panel need separate MOSFET (6 LED Panels will need 6 seperate MOSFET) or can 1 MOSFET be connected to all 6 LED Panel ?
If I am using 6 LED Panels what should be the specification of Power Supply (Voltage & Amps) ?
If I use 6 set of MOSFET & LED Panels, can all MOSFETs be connected to a single PWM pin in ESP32 or does each MOSFET needs to be connected to separate PWM pins in ESP32 ?
Is the above circuit okay, or would you suggest some other components to be added apart from MOSFET?
What will be connection between power supply, LED and MOSFET.
I am guessing that 'Positive of Power Supply --> Positive of LED Panel', 'Negative of LED Panel -->  Source of MOSFET' and 'Drain of MOSFET --> Negative of Power Supply'. Kindly correct me if I am wrong.

Thanks.

To add more information regarding the LED panel:

It is 15W LED Panel (note it is not LED Bulb or LED Strip).
Link to LED panel is 15W LED Panel

Below is the picture of Driver that came with the LED Panel, note the below driver is non-dimmable.

Kindly help.


texts: clear Arduino as a global variable in Matlab

texts:
I'm trying to use Arduino in Matlab. cause I used Arduino in some function I had to define Arduino as a global variable.

clc,clear,close all;
global a
a = arduino();
.
some functions
.
clear a

at the end of my code I clear the variable but as I run the code again this error appear:

Failed to open serial port (user COM) to communicate with board Uno. ...
 Make sure there is no other MATLAB arduino object for this board.

I guess the global function can't be clear by clear command so I tried clear all instead clear in the last line. It works perfect as I run it again and again but as you know this is Matlab tips for clear all command

Using clear all causes MATLAB® to recompile previously cached code,
and can decrease performance.

I've tried delete(a) so the result was:

Error using arduino/delete
Cannot access method 'delete' in class 'arduino'.

any help would be appreciated.


texts:
I'm thinking about making my own "arduino" low power board but I have a question about the atmega328. Is the output voltage on the pins always 5v or it depends on the input voltage I gave to the atmega?

Thanks in advance.


texts: How to pass input from a Midi controller to a function?

texts:
I am trying to pass the input[], data1(pitch) from a Midi controller to the waitForButton function. When a key is pressed it sends data1(pitch) into the array input[], and when the key is up the array value goes to zero. But the input isn't being passed to the function as I am pressing the keys on the Midi controller. What am I missing?

void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
  data1 = MIDI.getData1();
  if (data1==48) { //C3
    Status[0][0]=1;
    noteOn(0,data1,100);
    input[0]=data1;
  }
}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
  data1 = MIDI.getData1();
  if (data1==48) { //C3
    Status[0][0]=0;
    noteOff(0,data1,100);
    input[0]=0;
  }
}

void readsequnce() {
  bool mademistake = false;
  int key;
  for (int index = 0; index < largestindex & mademistake == false; index++) {
    key = waitForButton(5000);
    if(key ==-1 || key != note[index]) {
      mademistake = true;
      state = 2;
    }
  }
}

int waitForButton(int laps) {
  int keyPressed= -1;
  int check;
  boolean keyBackUp = false;
  currentMillis = millis();
  // The number of ms since the program started running
  previousMillis = currentMillis;
  // Records the point when we start spinning the loop.
  // Keep spinning the loop until "delay" seconds have passed.
  while (currentMillis - previousMillis < laps & keyBackUp == false) {
    lcd.setCursor(16, 2);
    lcd.print(String(keyPressed));
    // Read the button and record when it has been pushed down.
    for (int i = 0; i < 25 & keyBackUp == false; i++) {
      if (input[i] != 0) {
        keyPressed = input[i];
        // Show the LED pushed.
        noteOn(0, keyPressed, 100);
        //  digitalWrite(leds[pin], HIGH);
        // It is possible the button is still being pushed.
        // This loop spins until the button is let up.
        while (currentMillis - previousMillis < laps & keyBackUp == false) {
          check = input[i];
          if (check == 0) {
            keyBackUp = true;
          }
          currentMillis = millis();
        }
        // Turn the LED pushed off.
        noteOff(0, keyPressed, 0);
        // digitalWrite(leds[pin], LOW);
        // See if they took to long.
        if (currentMillis - previousMillis > laps) {
          keyPressed = -1;
          // They took to long to let the button up so they lose.
        }
      }
    }
    currentMillis = millis();
  }
  return keyPressed;
}


texts: Resistor - Correct value for optocoupler, but dont have that size

texts:
I am making a shutter for my camera using a Arduino and an optocoupler.
I understand most of most parts, but unsure about the resistor because I don't have the correct size. 5V will be coming from the Arduino, and the 4N35 will need 1.3V 10mA. This leads to a 380Ω resistor.
Now I only have 100Ω, 220Ω, 330Ω, and 1kΩ resistors. I have read I shouldn't use anything lower than 380Ω and only use higher but 1kΩ seem a little too high haha.
Just looking for some pointers please.


texts: Can't reprogram atmega328p chips using nano as ISP

texts:
Using nano clone as an ISP on a breadboard- as shown here - http://www.martyncurrey.com/arduino-nano-as-an-isp-programmer/

Previously, it worked great.  However, recently, chips that I have bootloaded and programmed have, when added to the breadboard for reprogramming, caused the USB connection to drop.  The heartbeat LED on the nano also dims slightly which makes me wonder if it's a power issue?

Either way, this means that I can't program the chip.

Does anyone know how to fix this?  The breadboard circuit will happily program new chips.

The programs on the chips that aren't working often include blink on pin 19 on the DIP chip (D13) - and when I disconnect the link from this to D13 on nano, the USB connection is restored.

But otherwise I am very confused, have got about 7 chips with the same issue and would be great to fix it.

Ideas?  Thanks


texts: Trying to run Timer1 in ATmega2560 with assembly

texts:
I have a slight problem with Timer1 in arduino (ATmega2560) while coding it in assembly. I try to run the Timer1 in CTC mode - I configure everything well in my opinion, but the TCNT1 just doesn't increment each clock cycle, as it should. I checked the registers in Atmel Studio and everything seems okay, but maybe I forgot about something?

Here is the code

.ORG 0
jmp start

.ORG 0x22
call isr_toggle_PA0

.ORG 0x400
start:
LDI R16, HIGH(RAMEND)
OUT SPH, R16
LDI R16, LOW(RAMEND)
OUT SPL, R16 ; initialize stack pointer
clr r16

ldi r16, 0xff
out DDRA, r16 ; port A output
ldi r16, 0x00
out DDRD, r16 ; port D input
clr r16

ldi r20, 1<<OCIE1A
sts TIMSK1, r20 ; enable Timer1 A comapre match interrupt
sei

ldi r20, HIGH(25000)
sts OCR1AH, r20
ldi r20, LOW(25000)
sts OCR1AL, r20

ldi r20, 0b00000010 ; CTC mode, int clk;
sts TCCR1A, r20
ldi r20, 0b000000101 ; prescaler /1024
sts TCCR1B, r20
ldi r20, 0
sts TCCR1C, r20

; --- start main
main:

inc r16
rjmp main
; --- end main

isr_toggle_PA0: // toggle bit on PA0
    ldi r16,0x00000001
    in r17, PORTA
    eor r17,r16
    out PORTA, r17
    reti

Thank you and have a good day :)


texts: Powering two L298N motor boards with external supply

texts:
I have been struggling with this as I'm a complete electronics and arduino beginner. I am trying to power two DVD-drive stepper motors using two L298N motor boards.
For some reason, I can't figure out how to power them using external source.
I can connect one like this straight from the arduino and the motor spins properly:

I know this is bad because it could damage the arduino etc, so I tried to provide a separate power supply to the motor, which in this case is an iphone wall charger which provides 5V, 1A. I also tried with a power bank that supplies 5V, 1A. I wired it up like this but then the motors don't run:

I don't know what I am doing wrong. Any help would be greatly appreciated.


texts:
I've spent three days on this, and either I'm blind to something, or something just ain't right.
Doorbell. Front door switch and back door switch. Two interrupt service routines, one attached to each pin. Rudimentary debouncing in the ISR seems to work.
But for some reason, both interrupt routines are firing off when either of the switches is pressed. I've tried RISING, FALLING, LOW, CHANGE, and it all works the same. I tried INPUT_PULLUP and INPUT_PULLDOWN and changed the polarity on the switches. No change. I've tried different pins, digital, analog. Nothing seems to keep both ISRs from firing.
Pressing front door button, it should print:
front door high
Releasing front door button
front door low
Pressing back door button
back door high
Releasing back door button
back door low
But for some reason, both interrupt service routines are called when pushing either button. Here's what I actually get:
Pressing front door button:
back door low
front door high
Releasing front door button
front door low
Pressing back door button
front door WTF?
back door high
Releasing back door button
front door WTF?
back door low
Here's the code. I hope someone can see something I can't:
#include <Arduino.h>

#define FRONT_DOOR_SWITCH A2
#define BACK_DOOR_SWITCH A3

volatile int frontDoorStatus = 0;
volatile int backDoorStatus = 0;

void frontDoorIsr()
{
    static unsigned long last_interrupt_time = 0;
    unsigned long interrupt_time = millis();
    // If interrupts come faster than 200ms, assume it's a bounce and ignore
    if (interrupt_time - last_interrupt_time > 200) {
        if (digitalRead(FRONT_DOOR_SWITCH) == HIGH) {
            frontDoorStatus = 1;
        }
        else if (digitalRead(FRONT_DOOR_SWITCH) == LOW) {
            frontDoorStatus = 2;
        }
        else {
            frontDoorStatus = -1;
        }
    }
    last_interrupt_time = interrupt_time;
}

void backDoorIsr()
{
    static unsigned long last_interrupt_time = 0;
    unsigned long interrupt_time = millis();
    // If interrupts come faster than 200ms, assume it's a bounce and ignore
    if (interrupt_time - last_interrupt_time > 200) {
        if (digitalRead(BACK_DOOR_SWITCH) == HIGH) {
            backDoorStatus = 1;
        }
        else if (digitalRead(BACK_DOOR_SWITCH) == LOW) {
            backDoorStatus = 2;
        }
        else {
            backDoorStatus = -1;
        }
    }
    last_interrupt_time = interrupt_time;
}

void setup() {
    pinMode(FRONT_DOOR_SWITCH, INPUT_PULLDOWN);
    pinMode(BACK_DOOR_SWITCH, INPUT_PULLDOWN);

    attachInterrupt(digitalPinToInterrupt(FRONT_DOOR_SWITCH), frontDoorIsr, CHANGE);
    attachInterrupt(digitalPinToInterrupt(BACK_DOOR_SWITCH), backDoorIsr, CHANGE);
}

void loop()
{
    switch (frontDoorStatus) {
        case 0:
            break;
        case -1:
            Serial.println("front door WTF?");
            frontDoorStatus = 0;
            break;
        case 1:
            Serial.println("front door high");
            frontDoorStatus = 0;
            break;
        case 2:
            Serial.println("front door low");
            frontDoorStatus = 0;
            break;
    }

    switch (backDoorStatus) {
        case 0:
            break;
        case -1:
            Serial.println("back door WTF?");
            backDoorStatus = 0;
            break;
        case 1:
            Serial.println("back door high");
            backDoorStatus = 0;
            break;
        case 2:
            Serial.println("back door low");
            backDoorStatus = 0;
            break;
    }
}

Board is Adafruit Feather Express M4 (SAMD51)


texts:
void setup() {
  // put your setup code here, to run once:
  pinMode(3,OUTPUT);//data
  pinMode(4,OUTPUT);//clock
}

void loop() {
  // put your main code here, to run repeatedly:
//  byte sender=random(255);
  shiftOut(3,4,MSBFIRST,B111);
  delay(1000000);
  shiftOut(3,4,MSBFIRST,0);
  delay(1000000);
}

http://pdf.datasheetarchive.com/datasheetsmain/Datasheets-30/DSA-599035.pdf

Can someone help me with this over-sized blink example? The LED's not lighting up.


texts: Is it possible to directly set the registers that control the ADC clock on the Arduino?

texts:
Is it possible to directly set the registers that control the ADC in an Arduino Yun (micro-controller side is essentially a Arduino Leonardo) from a sketch or is there a specific file somewhere you must edit?

I am working on a project that collects a signal digitizes it and sends it through a digital filter. I looked up the Datasheet for the micro-controller on the Yun and wrote the code setting the registers associated with the ADC portion of the micro controller. The code setting the registers was something like REGNAME = 0x01;. Yet when tested several of the associated registers were unaffected. Pointers on the process to set the ADC manually without using the analogRead() function would be appreciated.

Edit:
My original code looked something like this:

void setup(){
    // register to turn on ADC
    REG1 = REG1 | 0x01;

    //register to set sample rate and set ADC to Free Running Mode
    REG2 = REG2 & 0x30;

    // register to set other settings
    REG3 = REG3 | 0xF1;
}

void loop(){
    // code to take samples from ADC
    // and send them through a digital filter here.
}


texts: How to avoid report of unsuitable sketch names?

texts:
I bought a kit of 37 sensors for Arduino, and downloaded all the example sketches. Now, when I try to start up the Arduino IDE I get a lot of frustrating messages like this:

... and I have to click "OK" on every one in turn before the IDE will start up.

Obviously I do not want to delete the sketches and their accompaniments, so I have tried to rename all the files and directories, with a shell script, to remove non-alphanumerical characters, but my understanding of shell programming is not good enough, so I have had no success.

I have made backups of the files in case things went awry with my scripting, and now see that these messages are repeated, as in the image, for the backup copies as well. I cannot find out how the Arduino IDE finds them, they are not in my Sketchbook folder.

I would be grateful for advice on either how to avoid these messages, or to edit the names so that they do not occur: I would be happy to edit the names of each sketch as I come to try it out, but I baulk at doing the lot at once.

I am using Linux Fedora 20.


texts:
So, I've been trying to make an Lcd display shield I got from ebay to work with arduino. Using this very simple code:

#include <LiquidCrystal.h>

#define RSPin 8
#define EnablePin 9
#define DS4 4
#define DS5 5
#define DS6 6
#define DS7 7

#define LCDColumns 16
#define LCDRows 2

LiquidCrystal lcd(RSPin, EnablePin,DS4,DS5,DS6,DS7);

void setup()
{
  lcd.begin(LCDColumns, LCDRows); //Configure the LCD
  lcd.setCursor(0,0);
  lcd.print("Hello, World!");
}

void loop()
{

}

Actually I've tried several simple examples, checked pins physically to make sure I'm using the right order, But no luck. backlight is on, no characters at all. Am I missing something? Or should just contact the seller to send another shield.


texts:
Lets say I have something that sends a command to the Arduino (for example, a PC sending through serial, Ethernet, etc). I want the Arduino to "check" what command it is and run a specific function linked to that command.

I don't need a very explanatory answer, just give me something so I can learn from. A sketch that shows a similar idea would be good, I can try to interpret it and adapt/remake for me.

The idea is to use the Arduino for a lot of different things. Let's say:

Turn a bunch of leds on/off;
Read data from a sensor and send it through Ethernet/I2C/Serial;
Control a servo.

But I want the Arduino to do that when I tell it to (in this case, sending the command through serial, etc). So let's say I send it 1, I'll want it to run the 1 function (turning the LEDs on/off).

I already took a tutorial course on Arduino programming, but I'm clueless on how to do this job.


texts: Arduino UNO - Fluctuation of inputs and outputs

texts:
I have some pots (100K) on my Arduino board. When I raise the value of one those resistance other pots are being changed (Not too much but it's significant). I have no idea what's going on. I tried to use a capacitor at the beginning of the circuit but didn't work.

These fluctuations change the value of my sensors too. When I raise the value of something other quantities change.

I'm powering up my Arduino using a USB cable.

Any ideas?


texts: Delay not working in function other than loop

texts:
So I just got an Arduino and thought I would play around a bit.

However not five minutes in I already ran into a problem.

I tried programming a simple SOS blinking light sequence. To get rid of code duplication I refactored the on and off turning of the LED into functions and then again refactored a short blink and a long blink function which are expected to turn the LED on for a short time and then for a long time.

The problem is the delay in those functions is completely ignored.

int ledPin = 13;

void on()
{
 digitalWrite(ledPin,HIGH);
}

void off()
{
 digitalWrite(ledPin,LOW);
}

void shortB()
{
 on();
 delay(1000);
 off();
}

void longB()
{
 on();
 delay(2000);
 off();
}

void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{
 shortB();
 shortB();
 shortB();
 shortB();
 longB();
 longB();
 longB();
 shortB();
 shortB();
 shortB();
 delay(5000);
}

My expected behavior would be that it does an SOS and then waits 5 seconds and repeats.

What really happens however is that it stay continuously lit for a second or so then turns off for 5 seconds.

Using

on();
delay(1000);
off();

In the main loop works so I guess it simply ignores the delays that are put into the other functions. My question would be why and ho do I fix it?

I know that I can use other timer function constructs however I really think this is something that should work by default.


texts: I read an article that said that shorting an IO pin to ground would destroy the pin.  I've done this before when I connected a buzzer to an IO pin and to ground without resistors, the buzzer is only 14 ohms so the current would be quite high through the pins.  Why is my Arduino still working,  and how should I know when to use resistors or what rating to use?


texts:
I can't configure at 192.168.240.1. It's giving me this message multiple times:

1- AJAX/HAR Error:0 has not allowed Arduino Configuration Wizard to complete.

Details of my board:

Arduino Yun V2.0.1 anders evinrud


texts:
I found code for a Teensy board and now I added just digitalwriteFast library to code and changed port to SPI for Arduino Mega. And now I get just one number out:

#include <SPI.h>
#include <digitalWriteFast.h>

//(other stuff for getting the ADS1526 to work is in the next tab
#define ADS_RST_PIN    48 //ADS1256 reset pin
#define ADS_RDY_PIN    47 //ADS1256 data ready
#define ADS_CS_PIN    46 //ADS1256 chip select

/*
CLK  - pin 52
DIN  - pin 50 (MOSI)
DOUT - pin 51 (MISO)
*/

//put the ADC constants here

double resolution = 8388608.; //2^23-1

//this needs to match the setting in the ADC init function in the library tab
double Gain = 64.; //be sure to have a period

double vRef = 5.0; //reference voltage

//we'll calculate this in setup
double bitToVolt = 0.;

void setup() {
 delay(1000);
 Serial.begin(115200);
 Serial.println("booting");
 //initialize the ADS
 pinMode(ADS_CS_PIN, OUTPUT);

 pinMode(ADS_RDY_PIN, INPUT);
 pinMode(ADS_RST_PIN, OUTPUT);

 SPI.begin();

 initADS();
 Serial.println("done init");

 //determine the conversion factor
    //do some calculations for the constants
 bitToVolt = resolution*Gain/vRef;
}

int32_t val1;
int32_t val2;
int32_t val3;

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

double value = 0;
for (int i = 0; i <1; i++){
 read_three_values();
 value += val1;
}

value /=1.;

 Serial.print(value,8);
 Serial.print("\t");
 Serial.print(val2);
 Serial.print("\t");
 Serial.println(val3);

//
//double value = 0;
//for (int i = 0; i <10; i++){
//  value += read_Value();
//}
//
//value /= 10.;
//value /= bitToVolt;
//
//Serial.println(value,11);
}

I don't know where to connect PDWN pin?

And I have this board:
https://www.ebay.com/itm/NEW-1PC-ADS1256-high-precision-ADC-module-conversion-24-bit-eight-channel/292541380872?hash=item441cd33908:g:uYUAAOSwLpda5BIZ:rk:1:pf:0

Greetings Matej


texts: Programming ATtiny85 with Arduino-IDE and an 8MHz external oscillator

texts:
I have a digispark ATtiny85 development board and I am using the Arduino IDE to program it along with the Arduino UNO as my hardware programmer.
I have successfully burned the fuses for both the internal 1 and 8 MHz RC oscillators using the original Arduino as ISP sketch (you'll understand why I said original in a moment), but as my application needs precise timing, I would like to use an external oscillator, however, every time I tried to burn/program the bootloader/fuses using the Arduino IDE and using the original Arduino as ISP, the avrdude spits the infamous (Yikes).
I searched online and found an updated version of the Arduino as ISP sketch, which is supposed to an updated version, it has only one downside, which is, it can't do anything other than burn/program the bootloader/fuses, meaning that it can't be used to program the ATtiny85 like the original Arduino as ISP could do.
So without hesitating, I tested it to burn/program the bootloader/fuses for the internal 1 and 8 MHz RC oscillators, and it worked perfectly, and as expected, it fails to upload the code.
But the original Arduino as ISP successfully uploaded the code.
When I tried to burn/program the bootloader/fuses for the external 8MHz crystal oscillator using the updated Arduino as ISP, it worked flawlessly... until I noticed that the ordinary Arduino as ISP can not upload the code anymore and I am presented with the infamous (Yikes!) error.
Let me elaborate the difference in the connections between the two sketches.
The updated Arduino as ISP generates a clock signal on pin #9, which connects to the CLKI of the ATtiny85 (AKA Pin #2 "PB3"), while the original Arduino as ISP does not utilize this pin at all.
I found the updated Arduino as ISP on the electronics stack exchange forum, but unfortunately I lost the link to the question which contained why is this updated Arduino as ISP is better.
I can provide both codes though if someone needs them.
I have my crystal connected in both cases, burning/programming the bootloader/fuses and while trying to upload my code.
This is the infamous (Yikes!) error which I was talking about.

This is my current wiring.

Please note that I connect pin #9 to the CLKI of the ATtiny85 (AKA Pin #2 "PB3"), only when I am using the updated Arduino as ISP.
This is the actual wiring.

My two questions are:

How could I burn/program the bootloader/fuses of the ATtiny85 to use an external oscillator of 8MHz or 16 MHz?
How could I upload my application code after burning/programming the bootloader/fuses?

I hope the answers elaborate how the connections would differ, if it would.
Thank a lot in advance.


texts: Share data between the two processors of the Arduino Yun

texts:
The linux processor runs a Python script from which I would like to send an array of integers to the Yun microprocessor. How can I do that?

And then, how can I retrieve and then use this array in my Arduino Sketch?


texts: Ethernet Shield 2 data to PHP server doesn't work

texts:
I am trying to send data via GET to my PHP server from my Ethernet Shield2.
This is part of my sketch:

char myserver[] = "www.myserver.com/";
if (client.connect(myserver, 80)) {
  Serial.print("Connected to ");
  Serial.println(myserver);
  client.print("GET /arduino/controller.php?");
  client.print("air_temp=");
  client.print(DS18B20_temperature);
  client.println(" HTTP/1.1");
  client.print("Host: ");
  client.println(myserver);
  client.println("Connection: close");
  client.println();
  client.println();
} else {
  // if you didn't get a connection to the server:
  Serial.println("Connection failed to Server");
}

The serial monitor displays "Connect to myserver.com" but my PHP code doesn't seem to receive the air_temp value from DS18B20_temperature. I checked this value and it's true.

However, when I try myserver.com/arduino/controller.php?air_temp=25 in my browser, the PHP code is running well.

What's going wrong with my code?


texts: Controlling a 5m LED strip with a Nano or Uno

texts: I'm wanting to control a 12V LED strip (5m, 60 LEDs per meter) with a Nano or Uno. I know from Adafruit that I'll need some power transistors but I'm not sure that I have the right type. I have 6 transistors labelled 30N06L, and I'm hoping they're equivalent to the ones used. Are mine ok to use, or do I need to buy others?


texts: How to power multiple LEDs with a microcontroller

texts:
I currently have a "tiny" setup and want to put a few (~20-30) 0402 LEDs on a 1:87 scale car. My current setup is an ATtiny85 USB Mini Dev Board powered by a 90mAh 3.7V LiPo battery which is connected to a TP4056 5V micro USB Lipo battery charger:

To my bitter disappointment one cannot connect the leds in series. I've read about charlieplexing which was a little mind boggling for me to comprehend.

I was going to break down the leds and pins as follows:

P0 - headlights (2x white 0402 LEDs) +  tail lights (2x red 0402 LEDs) - in series - in parrallel
P1 - blinkers (4x amber 0402 LEDs) - in series - in parrallel
P2 - siren (12x amber 0402 LEDs) - in series - in parrallel
P3 - beacon (2x blue 0402 LEDs) - in series - in parrallel
P4 - beacon (2x blue 0402 LEDs) - in series - in parrallel
P5 - beacon (2x blue 0402 LEDs) - in series - in parrallel

Question:

With space being limited inside the model car how would I be able to
drive 20-30 LEDs with the above set up?
I am in doubt that the models in the video use charlieplexing and use a similar microcontroller, how would they be doing this?
Would it be better for me use something like a Pro Micro ATmega32U4 5V 16MHz and spread the LEDs across the 16 pins (ie 2 LEDs per pin = total of 32 LEDs)?


texts: Arduino RGB IR Controller -> led always close to white

texts:
I use arduino nano.

When i use this code the rgb light on the fan is showing the colors right

int rossoPin = 11;
int verdePin = 12;
int bluPin = 10;
void setup(){
  pinMode(rossoPin, OUTPUT);
  pinMode(verdePin, OUTPUT);
  pinMode(bluPin, OUTPUT);
}
void loop(){
    for(int i = 0; i < 256; i++){
    rgb(255-i, i, 0);
    delay(10);
  }
  for(int i = 0; i < 256; i++){
    rgb(0, 255-i, i);
    delay(10);
  }
  for(int i = 0; i < 256; i++){
    rgb(i, 0, 255-i);
    delay(10);
  }
}
void rgb(int red, int green, int blue){
  analogWrite(rossoPin, red);
  analogWrite(verdePin, green);
  analogWrite(bluPin, blue);
}

,but when i use the full controller code it wont work nothing(ex.white color when it's on off state)

FULL CODE:
link to the code


texts:
I have written this code

const int A = 3;
const int B = 5;
void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);

}

void loop() {
  for(int i=1;i<=255;i++)
  {
    int j =255-i;
    analogWrite(A,i);
    analogWrite(B,j);
    delay(100);
  }
  for(int i=255;i>0;i--)
  {
    int j =255-i;
    analogWrite(B,j);
    analogWrite(A,i);
    delay(100);
  }
}

Is  this code correct? If yes then can it be modified in any way to make it better?


texts: Part of Board exploded when Peltier Plate was wired t(o Board

texts:
Photos and Screenshots: https://imgur.com/gallery/bpmJglE
By the way, I used a screenshot that was originally from this post: Have I bricked my Arduino Uno? Problems with uploading to board
Hey guys,
I was trying to wire two TEC1-12706 Peltier plates to my breadboard, and I saw that using the USB connection for power was not enough for both plates. So, I found a 19v--3.9A DC/AC adapter/computer charger and plugged it in to my Uno via the Power Jack port. The Peltier plates were not wired to the board when I plugged it in and everything looked fine, all the normal LEDs on the UNO lit up, etc. Then, I wired a peltier plate to my breadboard. As soon as I did, a part exploded, and grey smoke come out of the "L" light area. I unplugged it immediately. The next day, I plugged the adapter back into the Power Jack port and a screenshot is attached of some observations I made by touching the board. Photos of my Uno are also attached. As you can see, the "Slightly less hot but still burning part" is pretty much destroyed. The "L" light will not light up and as of right now I can't upload any code to it. Might be an unrelated issue so I will continue troubleshooting that, but it is still another observation. The test LED I wired is lit up, so I guess the board can still kinda function? I'm high school student and obviously a complete beginner. Will continue to do research on this. I really want to know what happened. Please help?  Thanks everyone.


texts: How do I call functions sequentially without using the Delay function?

texts:
I've been messing with the Adafruit Neopixel lib, and I'm trying to replace some of the delay functions with mills ( so that I don't block the serial port ). So far I have the following code;

void loop() {
  currentMillis = millis();

  colorWipe(strip.Color(255, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 255, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 255), 50); // Blue
  colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
}

void colorWipe(uint32_t c, uint8_t wait) {
  if (currentMillis - previousMillis >= 200) {
    for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      //delay(wait);
      Serial.println("Light");
      previousMillis = currentMillis;
    }
   Serial.println("Done");
  }
}

The issue I'm running into ( and I do understand this is fundamental concept in Arduino programming ) is how to run sequential functions, like the ones in loop, while still not blocking the main loop. The way this currently functions, it runs through the first colorWhipe loop and then just keeps iterating.


texts:
I'm working on gesture gloves project, which means it detect hand movement or current position, to be used in something else such as controlling a car.

I wanted to measure how much the wrist joint is bending, i used flex sensor, but when the wrist is bending while the fingers are pointing to upward ( _| ) the flex sensor became more longer in length than the wrist.. which make it hard for sewing ..

is there any alternative sensor?


texts: Best 2a stepper motor driver for Arduino Uno

texts:
What is the simplest (from a user/install standpoint) 2a stepper motor driver for an Arduino Uno?

I would like something simple and easy to stack like the Adafruit Motor/Stepper/Servo Shield for Arduino v2 Kit  but unfortunately it only handles 1.2a. I can do basic soldering but I would like to keep things simple and physically stacked or connected if possible. I don't want to use jumpers or a breadboard.

I am trying to run this stepper to simply open and close a door every few hours:
14:1 Planetary Gearbox High Torque Nema 17 Stepper

Using this battery from Amazon:
ExpertPower EXP1250 12V 5Ah

If I'm missing anything please let me know. Your feedback is appreciated.


texts: Does an I²C IO Expander needs additional resistors for outputs?

texts:
I have following setup (see also schematic in the end)

Arduino Nano is connected via I²C to the PCF8575C (link) IO Expander.
Both, SCL and SDA have 10kOhm pull-ups to 5V.
The Expander pins are connected to a MOSFET-driver that turns on/off 12V LED stripes.
The Expanders Bus address is set via Expanders A0-A2 pins to 0 (0x20).
The MOSFET driver pins have to be pulled to logic 1 (above 2.2V) in order to turn on the stripe.

Currently Arduino runs an blink example, that turns all Expander IO pins on/off every second (using Arduino Wire Library), but the MOSFET-driver does not turn on/off any Stripe.

I can manually turn on Stripes by connecting MOSFET-driver pins to Arduinos 5V (or 3.3V)

The power supply to the IO Expander is O.K.

By measuring the resistance between GND and IO pins of the Expander, I can see that it alternates every second (so I²C communication to the Expander works also)

Curious thing: While measuring this resistance (holding the multimeter test leads) to GND and to the IO pin of Expander, the MOSFET-driver turns the Stripes on and off! When I take the test leads away it stops working! Magic?!

What am I missing? Do the output pins of the PCF8575C need some extra pullup/pulldown resistors or something else?

Thank you in advance!

Schematics:


texts: What does an Arduino do if the serial connection is closed on the other end?

texts:
I have a simple method that simply waits for an input, computes a response, and sends it:
void loop() {
  if (Serial.available() > 0){
    input = Serial.read();

    if (input == 10){
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);

      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = PulseDuration(echoPin, HIGH, 6000);
      distance = duration * 0.00034/2;  // 0.00034 m/us is speed of sound

      Serial.println(distance, 4);
      }
  }
}

My question: What happens to the arduino if I close the serial connection from the receiving end while it's printing out data (in the last line of the loop)?
Context and motivation:
The program works well most times. I can open a python program that sends the requests and prints out the reply using pyserial. After I close the python side and reopen it, connection is set and I can start listening on the side nicely just like the first time. Sometimes, however, when I try to restart the python program, I get a connection error saying that the port is already opened (I'm running in Windows.. there are tons of posts about this problem, but none of them have been helpful). Some other times, when connecting with the python program (which connects with connection = serial.Serial(self.arduino_port, 9600, timeout=0) it just blocks and doesn't connect, it doesn't give the "port already opened" error, and it doesn't advance to the next statement.
I am confident I did close the previous python run before attempting a new one (process explorer shows no active python programs running, it also shows no open processes using a serial handler). I'm not here to solve that problem directly, though, just to ask a related question.
I'm also confident running connection.close() does not terminate the arduino program, as I have been able to restart my python program without having to reset the arduino or anything, suggesting the arduino kept running its loop after I closed the connection on the python side.
All that to say that my latest hypothesis is that these issues arise when I close the serial connection connection.close() while the arduino is printing, but because the port is closed, that Arduino is stuck and cannot do the Serial.println(), as the USB never asks to flush the data in its buffer.
Is this possible/does it make sense? What happens to the arduino if I close the serial connection while it's printing out data?
I'm not posting my python program here as it's not directly relevant to the question and I can't seem to make a minimum reproducible program that doesn't expose confidential code.


texts: ESP - Nodemcu amica - attachInterrupt crash program

texts:
I get new boards from the shop but they are little different from the previous version. I got software what works ok on Nodemcu lolin v3 now I get Nodemcu Amica what is almost same board but if I got attachInterrupt function in the program it crashes immediately.

    attachInterrupt(6, bowlingCall, RISING);
//attachInterrupt(digitalPinToInterrupt(D1), statekCall, RISING);

I try different pins but not change. I debug all program(comment all out and left just attachInterrupt and it crashes again).

    ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld

The board cycle in the reboot sequence, even serial output do not work ok. Why did esp crash at attachInterupt on this board?


texts:
I know little about electronics in general. I wanted to connect Arduino, and play a tone using tone() through my home speakers.

I've used a 1/8'' audio jack and connect ground to ground and left/right to pin 2. Run it and it was too loud.

Then I read the specification and it says,

Input impedance = 20 kOhm

Input sensibility = 400mV +/- 50mV

Arduino sends 5V so that should be a lot. Did I damage my speaker? They still work.


texts:
I have a Mega 2560 with a ramps 1.4 shield. I noticed when I turn on the 14v power supply the mega would also power up and run.

Am I damaging it running it at 14v? If not is there a solder or jumper somewhere that I can set it to only run the mega/logic on the usb power? The 14v is just for the stepper motors.


texts:
when I upload the code to my leonardo board it just stuck on uploading, like this:

could someone help me with this?


texts: How to extract latitude and longitude from GPS

texts:
I want to extract longitude and latitude from GSM/GPS module and then upload it to thingspeak. I am using sim808 GSM/GPS module and AT+CGPSINF=0 to get GPS location information sentence (CGPSINF: 0,6.823375,80.001038,36.300000,20170705124133.000,0,10,0.037040,47.410000
). I want to extract longitude and latitude from it. Does anyone know how to do it? I am not an expert in programming. someone told me to use strtok. But I don't know how to do it. Does anyone have any Arduino code to do this?

I tried DFRobot SIM808 library to collect GPS data. it works like charm. But the problem was, my upload code didn't work when i was using the library to collect longitude and latitude in the same code.

This is my web upload code.

#include <SoftwareSerial.h>
#include <String.h>

SoftwareSerial mySerial(10, 11);//(2,3)

void setup()
{
  mySerial.begin(2400);   // the GPRS baud rate 9600
  Serial.begin(2400);    // the GPRS baud rate 9600

  delay(1000);

  ShowSerialData();

}

void loop()
{
      Send2Pachube();
  if (mySerial.available())
    Serial.write(mySerial.read());
}
void Send2Pachube()
{
  mySerial.println("AT");//start with attention
  delay(1000);

  mySerial.println("AT+CPIN?");//check for the sim card
  delay(1000);

  mySerial.println("AT+CREG?");//check for registration and access technology of cell
  delay(1000);

  mySerial.println("AT+CGATT?");//check whether the device is attached to GPRS.0Detch,1Attch
  delay(1000);

  mySerial.println("AT+CIPSHUT");//shut packet data protocol context
  delay(1000);

  mySerial.println("AT+CIPSTATUS");// returns the current connection status
  delay(2000);

  mySerial.println("AT+CIPMUX=0"); //create multi-IP connection(0=single connection)
  delay(2000);

  ShowSerialData();

  mySerial.println("AT+CSTT=\"hutch3g\"");//start task and setting the APN,
  delay(1000);

  ShowSerialData();

  mySerial.println("AT+CIICR");//bring up wireless connection
  delay(3000);
  ShowSerialData();

  mySerial.println("AT+CIFSR");//get local IP adress
  delay(2000);
  ShowSerialData();

  mySerial.println("AT+CGPSINF=0");//get GPS
  delay(2000);
  ShowSerialData();

  mySerial.println("AT+CIPSPRT=0");//starts a TCP or UDP connection
  delay(3000);

  ShowSerialData();

  mySerial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//start up the connection
  delay(6000);

  ShowSerialData();

  mySerial.println("AT+CIPSEND");//begin send data to remote server
  delay(4000);
  ShowSerialData();

  String str="GET https://api.thingspeak.com/update?api_key=FF19NVWMPZEWX0XK&field1=100";
  mySerial.println(str);//begin send data to remote server
  delay(4000);
  ShowSerialData();

  mySerial.println((char)26);//sending
  delay(5000);//waitting for reply, important! the time is base on the condition of internet
  mySerial.println();

  ShowSerialData();

  mySerial.println("AT+CIPSHUT");//close the connection
  delay(100);
  ShowSerialData();
}
void ShowSerialData()
{
  while(mySerial.available()!=0)
    Serial.write(mySerial.read());
}


texts:
My goal is to have my Arduino fire two stepper motors.  They need not be simultaneous. I'm using an Arduino Uno with 2 motor shields - specifically, the Seeed Studio Motor Shield v1.0. I know this shield uses D8-13.

Question is, how can I get the Arduino to use both shields?  Is there a way to make one of the shields take D0-D7?  If I could do that that'd be great. As far as I can tell, there's no way. The motor shields cannot be physically mounted either.


texts: Connecting microSD reader and e-paper display to Nano at the same time?

texts:
Pretty much as the question states, I'm wondering if it's possible to connect (this: https://www.waveshare.com/7.5inch-HD-e-Paper-HAT.htm ) 7.5" e-paper display that has raspberry pi HAT and an SD card reader to Arduino nano/micro for reading images off SD and displaying on the screen. I'm an novice and a not sure if i can use the same pins for multipurpose
Thanks!


texts:
Just a basic query;

On my understanding of LED Matrix's, The following would light up 4 LEDs.

But what if I only wanted to light up just 3 of those LEDs? The circuit still needs the same inputs, since power will continue across all columns/rows

Thanks

Tom


texts: Serial print message results in gibberish

texts:
I'm trying to print messages to the serial monitor, and all I get is some unreadable format.

Looping Serial.println("Wait...!"); gives me the following results:

ö’ö’ƒÕ•¬ƒ´¼Õƒö“ƒ²ƒƒƒ¬‘¼¬Õ”’“ƒ¬•

Why is it unreadable, and how do I make it print a readable format?


texts: Arduino Nano - 5V pin drops to 3.3V when load is connected

texts:
I have a Nano (with ATmega328) board that I am using along with a GPS module, an LCD and a potentiometer to make a small GPS unit that will tell the location. Long story short, when powered externally using a ~9V source, the 5V output pin behaves weirdly.

Whenever the GPS is disconnected (LCD is still connected and lights up), the pin outputs 5V. Whenever I connect the GPS, the voltage drops to ~3.3V. I have read this question and it confirms my suspicions that the voltage regulator is to blame. However, the voltage output seems to be fine whenever GPS is not connected - not something one would expect with a faulty voltage regulator.

Could you please suggest where to look for a solution or perhaps some tests to run to narrow down the possible problems?


texts: Difference between /dev/ttyACM0 and /dev/ttyS0 (Arduino IDE ports under Linux)

texts:
I use the Arduino IDE to upload sketches to my Arduino Uno. My OS is Linux Ubuntu 14.04 LTS. The Arduino IDE has two ports by default for communication with the Arduino Uno:

/dev/ttyACM0
/dev/ttyS0

What is the difference between these two ports ?
What does "ACM0" and "S0" mean ?
Are there configuration files somewhere in the OS folder structure that describe the parameters of these ports ?

I know that when I select /dev/ttyACM0, I am able to send data to my Arduino Uno. However it does not work when I select /dev/ttyS0.

I just want to better understand what these ports are exactly.