texts: i am having Strange issues when trying to read form gps serial connection

texts:
I have an Adafruit Ultimate GPS connected to a MEGA2560. I am trying to get the data from the buffer and do other data processing at the same time, however. when i allow other processing to be done the output becomes garbled such as below. the first out is correct and then becomes garbled and outputs now useful data.

16:34:54.466 -> $GPGGA,163453.155,,,,,0,00,,,M,,M,,*7F

16:34:57.111 -> $GPRMC,163453.155,V,,,,$GP$GPGGA,1$GPGGA,$GPGGA

    void loop()
    {

    GetTotalPressure();
      char c = GPS.read();
      Serial.print(c);
       if (GPS.newNMEAreceived()) {

        if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
          return;  // we can fail to parse a sentence in which case we should just wait for another
      }
      if (timer2 > millis())  timer2 = millis();

      if (millis() - timer2 > 1000) {
        timer2 = millis(); // reset the timer
    GPSScreenUpdate();
      SDcardSave();

      }

When GetTotalPressue is commented out The GPS serial output is correct when it is no the error above happens.

GetTotalPressure is below the sensor is connected to a I2C bus

void GetTotalPressure() {
  Totalpressure = ms5611.readPressure();

Many Thanks


texts: Arduino is running as a server, but want to occasionally act as a client to update time

texts:
My Arduino (actually an ESP32-based Adafruit HUZZAH32) is running as a wifi server. Its main job is to service GET requests from a user, and to periodically turn devices on and off based on the commands implicit in those GETs.

It needs to keep an accurate time/date - in order to turn devices on/off as directed.   My cheap real-time clock is off a couple seconds or more per day.   So I figure I'll use code such as the example at:

https://randomnerdtutorials.com/esp32-ntp-client-date-time-arduino-ide/

... in which the Arduino creates a client to get the time from an NTP server.  Once a day (e.g. checking for the RTC time to be 00:00hrs in my "loop"), I'll adjust the RTC using NTP.

Looking around, it sounds like this is ok, for the Arduino to act as a client, as long as it's not actively servicing a client (the user's GET requests).  Do I have that right ?   Need I worry that a user might be sending a GET when that happens ?


texts: For an ESP, does the RESET or enable (EN) button always need to be pressed to start the Access Point? How to do it without?

texts:
Is there a way to start an ESP Access Point (AP) without pushing a button? All these are set up that way:

AP circuits4you
AP LastMinuteEngineers
AP MicrocontrollersLab
AP RandomNerdTutorials


texts: I have connected my motors to L298N and it in turn to arduino. My battery is ~18 V and i used a boost converter to get 12.99V. When I run my program on Arduino Mega, I check the output voltage from the motor drive and observe that it begins from somewhere 11.99V and goes gradually down like 11.70,11.63,11.55..... till 4.03 V then it does not go down. I am attaching my circuit as a photo here. I hope sonebody could help me to find my mistake


texts: FFT (or similar) library for the Arduino

texts:
I'd like to build a "low fidelity" spectrum analyzer to run on an Adafruit Trinket Pro. My primary goal is to intrigue my seven year-old niece with something that can be hacked. The plan is to pick up sound from a violin with a mic and use a set of 5 or 6 NeoPixels to represent octaves and use color for amplitude.

My first pass at this used Amanda Ghassaei's frequency detection code. It kind of worked, but seemed to be having problems with complex waveforms. After doing some more reading and looking at simple spectrum analyzers it seems that I'd do better using something like a FFT to collect the frequency information. It also seems that that might be stretching the capability of an Arduino…

Are there any FFT libraries that run well on the Arduino (over a range of about 200 to 4000 Hz)? Or are there other approaches that might work better?


texts: Using MPU6050 with ESP32 Cam- MPU Not Detected

texts:
Hi I'm trying to build a self balancing robot using my esp32 cam, but so far I haven't been able to setup my mpu6050 with it.I'm using the adafruit libraries with the given example sketches.
The only thing I've done different is using two different SDA , SCL pins. So to get that done in the software I have made the following change to the Adafruit_I2CDevice.cpp file, where the TwoWire.begin() happens.

This is the tutorial I'm following, Click Here
So Far this is What the Serial Monitor shows me
Adafruit MPU6050 test!
Failed to find MPU6050 chip

Any help to get my ESP32 to work with the MPU6050 is highly appreciated.
Also note I managed to read the bare values from the MPU using only the Wire.h library.The reson I want to use the Adafruit library is because it makes use of the DMP on the MPU6050.


texts: What is the best arduino board for a robotic arm?

texts:
In my university we need to buy arduino boards and kits to build a moving robotic arm, that moves up and down and clockwise in a specific degree (almost like humans's).

So, what's the most suitable arduino board to build this arm?
I suggested to use the basic UNO board, but we may need to use relays (for example) if the power source is 12volts. So there is should be a better one.

My regards.


texts: Multiple sensors connected to Arduino MEGA 2560 Serial ports


texts:
My traffic light code for the Arduino doesn't run. I was wondering if anyone could point out where my issues lie. The red and green LEDs should be on for 15 seconds and the amber on for 5 seconds.

#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdint-gcc.h>
/*15 second interrupt*/
#define INTERRUPTS 975

/*
 * col = current colour of light.
 * 'g', 'a', 'r', 'o'
 */
volatile uint8_t count;
volatile char col;

ISR(TIMER0_OVF_vect)
{
    count++;
    if (count >= INTERRUPTS){
        if (col == 'g'){
            /*switch to amber*/
            col = 'a';
            /*reset counter*/
            count = 0;
            /*timer counter to 171 as we only need 85 clicks for 5s*/
            TCNT0 = 171;
            PORTD = 0b00000010;
        } else if(col == 'a'){
            col = 'r';
            count = 0;
            TCNT0 = 0;
            PORTD = 0b00000100;
        } else if (col == 'r'){
            col = 'o';
            counter = 0;
            TCNT0 = 171;
            PORTD = 0b00000010;
        } else if (col == 'o'){
            col = 'g';
            count = 0;
            TCNT0 = 0;
            PORTD = 0b00000001;
        } else{
            return;
        }
    } else{
        if(col == 'g' || col == 'r'){
            TCNT0 = 0;
        } else if(col == 'a' || col == 'o'){
            TCNT0 = 171;
        }
    }
    return;
}

int main(void)
{
    /* normal mode */
    TCCR0A = 0b00000000;
    /* prescaler = 1024 */
    TCCR0B = 0b00000101;
    /* enable overflow interrupts */
    TIMSK0 = 0b00000001;
    TCNT0 = 0;
    sei();
    /*Initialise output*/
    DDRD = 0b11111111;
    count = 0;
    col = 'g';
    PORTD = 0b00000001;
    while (1){
    }
}


texts: 47Effects MIDI Library and serial debugging

texts:
I noticed that since I use the MIDI library from 47effects, I cannot use the print(ln) for the serial port for debugging purposes, neither I can find it in the documentation.

It states that the MIDI library uses the serial port, but I really miss the serial port now for debugging.

Update: so my question: The MIDI library uses the RX (pin 0) and TX (pin 1) on my Arduino One. However, I think the internal Serial.print/println also uses these same pins, so I was wondering how I can use Serial.print and Serial.println statements being visible on the Arduino IDE Terminal (emulator) while using the MIDI library.


texts:
Firstly, let me say that I'm new to using I2C devices, especially with Arduino. I have an 8-bit DAC (LTC2631) that I'm trying to control with an Arduino Uno. I thought I would be able to use the standard Wire library protocol to talk to it, but I'm not getting any response. Here's what I've tried:

#include <Wire.h>

void setup() {

    Wire.begin();
}

void loop() {
    Wire.beginTransmission(0x11); //specify device's address

    Wire.write(150); //send a test value

    Wire.endTransmission();
}

Am I missing something obvious? Or are not all I2C devices compatible with  Wire?


texts:
I have this if statement:

if (now.hour() == 5 && now.minute() == 10 && now.second() == 0 && now.dayOfTheWeek() != 1 && now.dayOfTheWeek() != 7){

Is there a way to condense that for the purposes of saving on some bytes?

Ultimately trying to say "At 5:10 every weekday do X"


texts:
i want to operate a relay with an ARDUINO UNO, but i want to use a separate power supply for the relay. Ive seen relays with VCC and jVCC (dont know what that is), but mine only has this pins: GND, IN1, IN2, VCC.
how should i connect it to the Arduino and the external power supply?


texts:
I am looking for the source and/or proper definition for the int() function.
I have searched through the source in Arduino.app, without much success.

The reference gives a terse explanation

int(x)
 x: a value of any type
 Converts a value to the int data type

Passing 1, '1' or 49 returns the int 1. I haven't tested other types.

This seems to be an Arduino specific function - it doesn't seem to be in any c/c++ library.


texts:
I'm working on code that will control micro servo. I use generic servo and built-in library for controling servo. Microcontroller is generic STM32.
Controlling servo Works as expected. But I don't want next behavior - attach() function sets servo to 180°(maybe 0°, not sure).
In my project I want next:

Servo stays at angle before going off/reboot
Servo goes to 90° after turning on/reboot

I googled about this problem and tried with write(90); before attach() in setup() function. Servo goes to 90° but after like 50ms attach() stops write(90) function and it goes back to 180°. So this didn't solve my problem.
Next I've open Servo.cpp and found that attach() function contains next code:

    bool Servo::attach(uint8 pin,
                   uint16 minPW,
                   uint16 maxPW,
                   int16 minAngle,
                   int16 maxAngle) {
    timer_dev *tdev = PIN_MAP[pin].timer_device;

    if (tdev == NULL) {
        // don't reset any fields or ASSERT(0), to keep driving any
        // previously attach()ed servo.
        return false;
    }

    if (this->attached()) {
        this->detach();
    }

    this->pin = pin;
    this->minPW = minPW;
    this->maxPW = maxPW;
    this->minAngle = minAngle;
    this->maxAngle = maxAngle;

    pinMode(pin, PWM);

    timer_pause(tdev);
    timer_set_prescaler(tdev, SERVO_PRESCALER - 1); // prescaler is 1-based
    timer_set_reload(tdev, SERVO_OVERFLOW);
    timer_generate_update(tdev);
    timer_resume(tdev);

    return true;
}

What should I do to fix this problem? Servo will adjust angle of PCB which holds LEDs. PCB will be in case and angle of 90° is default angle. 0°/180° will either destory servo or brake case/PCB/something else.


texts: What is the maximum "wattage" can be pushed into an ATMega328 ADC pins?

texts:
I was doing some Ohm's Law calculations to calculate the voltage output from a 2-resistor voltage divider, the input will be with a maximum of 12 volts, I want the ATMega328 to measure that voltage, so I simply thought of putting two resistors in series with values of 330 ohms and 220 ohms like this:

simulate this circuit – Schematic created using CircuitLab
Theoretically on paper the maximum voltage outputting from the node going to the ATMega328 is ~4.8V, but I want a special safety feature, I want to put in mind that at anytime the ground connection can be hung open (to simulate a lose breadboard connection, bad soldering joint etc...) now based upon my understanding if there is no ground connection, the voltage going to the Arduino will be 12V which is a killer, as after looking on the ATMMega328 datasheet it states that

28.1 Absolute Maximum Ratings. Voltage on any pin except RESET with respect
to ground => VCC + 0.5

The current will be limited by the 330ohm resistor to only 36mA which I think is a lot, I thought of doubling the resistors values to 330000 and 220000 by that the current will be limited to only 36uA. Again based upon my understanding there is still 12V going to the Arduino but wouldn't it directly drop if the ground connection was cut off ? That's why I ask what is the maximum input power to an Arduino?


texts: Solution for simple multi-Arduino communication network (or alternative?)

texts:
I know similar question has already been discussed here but I could not get clear answer.
Here is the thing: I have one master device - Mega2560, and multiple (about 9 but could be expandedin future) I2C perfiferals - displays, that can have one of two possible I2C IDs - limitation by the manufacturer. As I can't connect and talk to them from a single I2C bus I chose to attach each two of them to a Mini-Pro's I2C pins and connect the 5 Mini-Pros to the master. The question is am I going to the right direction, and which connection would do the trick? I2C is obviously out of question, so the remaining are UART and SPI. UART would require some external hardware to cope with multiple outputs from the slaves, SPI would require additional pins from the master for chip select signal.
Data rates are not high - min 10-20 kbps.
I think the SPI offers better solution, but I'm no expert, what do you think?

Cheers!

Stefan


texts:
I am making an IoT device with the MKR1000.

As a part of the process, I would like to set up an HTTPS connection to https://hit.tl8.co/api/ping (This is a website I have made and control).

The problem is that client.connect(url, 443) is returning false. I have tried normal HTTP and the URL works on a browser. I can also access https://www.google.com. The code is a small variation of the example HTTP client.

As such, I believe that the TLS cert I am using is not accessible by the MKR1000. Running this report shows that it is a RSA 2048 bits (e 65537) with SHA256withRSA cert.

Is there a way to get the MKR1000 to accept this cert? Failing that, what changes do I need to make to this cert for it to work?

Is there a software solution to get this cert working?


texts: Generate 2 PWM signals Vc and Vh from Arduino Uno

texts:
I want to generate two PWM signals VC and VH to give input to the gas sensor  with the duty cycle mentioned below. I also want to take the reading from the same sensor at the same time using Arduino Uno.

[

I am confused how to proceed with the code in Arduino Uno.


texts:
I'm using a MacBook Pro Mojave 10.14.6 to code genuine Arduinos. Been working with multiple Uno R3s, no issue. Got a genuine Nano and get the following error: ser_open(): can't open device "/dev/cu.usbmodem14201": No such file or directory

The USB cable I'm using works fine with a cheap Chinese Uno clone, so there are data pins in the cable.

I followed instructions to delete the kext file, rebooted, installed CH341SER_MAC file and rebooted. Still getting the error message. I notice that others have asked this question; where are the answers? Thanks in advance.


texts: Receiver xbee receiving data while the Transmitter is powered off?

texts:
My receiver xbee is receiving data even if the transmitter is disconnected , so if i am sending the string hello world , the receiver will repeat this string .

void loop() {
    Serial.println("Hello");
    delay(1000);
}

void loop() {
     if(Serial.available()>0){
         Serial.print((char)Serial.read());
     }
}


texts: Reading I2C sensors with a timer interrupt

texts:
I would like to read a sensor connected via I2C using Timer3 and Arduino Mega. Values are read from the sensor in the interrupt service routine and timer3 is set to trigger an interrupt at 200Hz.

Step I: testing the timer

I tested the timer using a counter and incrementing its value in the ISR. The output is displayed every second. It works!

200
201
200
201

CODE

// Timer variable
volatile int cont=0;

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

  setupL3G4200D(2000); // Configure L3G4200  - 250, 500 or 2000 deg/sec
  delay(1500); //wait for the sensor to be ready

  // Initialize Timer
  cli();
  TCCR3A = 0;
  TCCR3B = 0;

  // Set compare match register to the desired timer count
  OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
  //OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz

  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  k = micros();
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  cont=0;
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

Step II: Reading values from the sensor in the ISR

Now I add the I2C function in the Interrupt Service Routine, but the program is blocked after the calcBias() function which reads from the sensor, measures and saves the acquisition time in the samplingTime variable.

CODE

// Timer variables
volatile float phi=0;
volatile float theta=0;
volatile float psi=0;
volatile int x = 0;
volatile int y = 0;
volatile int z = 0;
volatile int cont=0;

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

  setupL3G4200D(2000); // Configure L3G4200  - 250, 500 or 2000 deg/sec
  delay(1500); //wait for the sensor to be ready

  calcBias():
  Serial.print("Readings take: (us)");
  Serial.println(samplingTime);

  // Initialize Timer
  cli();
  TCCR3A = 0;
  TCCR3B = 0;

  // Set compare match register to the desired timer count
  OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
  //OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz

  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);

  Serial.println("Enabling interrupts..");
  // enable global interrupts:
  sei();

  k = micros();
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  Serial.println(z);
  cont=0;
}

ISR(TIMER3_COMPB_vect)
{
  // Update x, y, and z with new values 2.5ms
  getGyroValues();
  cont++;
}

void getGyroValues()
{

  //starting samplingTimer
  samplingTime = micros();

  // Gets the angular velocity from the sensor
  byte zMSB = readRegister(L3G4200D_Address, 0x2D);
  byte zLSB = readRegister(L3G4200D_Address, 0x2C);
  z = ((zMSB << 8) | zLSB);

  samplingTime = micros()- samplingTime;
}

void calcBias()
{
  Serial.println("Bias");

  // Reads sensors and display three values
  getGyroValues();

  [...]

  Serial.println(bx);
  Serial.println(by);
  Serial.println(bz);
}

void writeRegister(int deviceAddress, byte address, byte val)
{
    Wire.beginTransmission(deviceAddress); // start transmission to device
    Wire.write(address);       // send register address
    Wire.write(val);         // send value to write
    Wire.endTransmission();     // end transmission
}

int readRegister(int deviceAddress, byte address)
{
    int v;
    Wire.beginTransmission(deviceAddress);
    Wire.write(address); // register to read
    Wire.endTransmission();

    Wire.requestFrom(deviceAddress, 1); // read a byte

    while(!Wire.available())
    {
        // waiting
       // Serial.println("No Data");
    }

    v = Wire.read();
    return v;
}

I thought that the interrupt frequency was to high and I tried with 80 Hz and 20 Hz. Same results.

Here is the output:

starting up L3G4200D
Bias
4.00
0.00
-3.00
Read


texts:
I'm trying to communicate between two NRF24L01+PA+LNA modules.
I know that NRF24L01+PA+LNA modules are consuming a lot of power and here is my 3.3V power circuit.

The LM317 datasheet says it can output up to 1.5 Amp.
I'm not using Arduino, I'm using STM32F103 blue pill and I'm powering it from this single LM317 linear voltage regulator.
I'm using 1100 mAh, 8.4V LIPO battery, one for Transmitter module(NRF24L01+PA+LNA and STM32 Blue Pill) and second one for receiver module (also with NRF24L01+PA+LNA and STM32 Blue Pill).
So my problem is that, when I'm TOUCHING the Transmitter's antenna somewhere in the middle with my FINGERS, then it transmits; If I'm not touching the antenna, it does not transmit.
I also added additional 100uF polar capacitors between NRF24L01+PA+LNA's VCC and GND, but it does not help.
What else can I do?


texts: Setup of Arduino Uno as ArduinoISP for programming attiny45

texts:
I have an Arduino Uno SMD and an attiny45, which I want to use as a sensor communicating via i2c. For a first step in finding out how to work with the attiny45 I just want to use the attiny as controller for a blinking led.
When first setting up the Arduino as "Arduino as ISP" some questions came up:

I found a lot of different information about wheter or not to use a capacitor between RESET and GND on the Arduino. Also the capacity differs between 0.1uF and 10uF. Unfornately, I found not a single comment on why this capacitor is needed (or not) and which capacities are suitable. All tutorials used electrolytic capacitors (which I only have in 100uF at hand). I have 10nF and 0.1uF at hand but only the film capacitor type. It would be brilliant if some could help me with deciding if I should use a capacitor, which one is suitable and what's the reason for using it.

My second question is about the clock rate I should set in the Arduino IDE. I added the board package from https://github.com/SpenceKonde/ATTinyCore to my Arduino IDE, which offers a large variety of clock rates in the tools dropdown menu. In some tutorials they mentioned that it's crucial to pick the correct clock speed to avoid wrecking the attiny. But, unfortunately, the mentioned clock speeds vary between "1 MHz (internal)" and "8 MHz (internal)". In the attiny45 datasheet (http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf) I found the "Calibrated Internal Oscillator" to be the clock set up in freshly shipped chips, which I understand to operate at 8 MHz. But, the datasheet also says, that the CKDIV8 fuse is set on shipment, which leads to a clock prescale value of 8 and to a clock rate of 1 MHz. I'm highly confused... Maybe someone here can help me to find the correct clock rate to set.

I hope I didn't forget any important information. If so, please let me know.
Kind regards and thank you in advance,
Matthias


texts:
I am trying to learn how to use a shift register to control 8 LEDs but for some reason my shift register is misbehaving and none of the LEDs are lighting up. I imagine that it's a problem with my wiring? I have replicated the circuit on 123D Circuits.

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

void setup() {
  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  // count from 0 to 255 and display the number
  // on the LEDs
  for (int numberToDisplay = 0; numberToDisplay < 256; numberToDisplay++) {
    // take the latchPin low so
    // the LEDs don't change while you're sending in bits:
    digitalWrite(latchPin, LOW);
    // shift out the bits:
    shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);

    //take the latch pin high so the LEDs will light up:
    digitalWrite(latchPin, HIGH);
    // pause before next value:
    delay(500);
  }
}


texts: Can all Arduino Due pins be used as digital input/output?

texts:
I am using an Arduino Due for a project. I am running out of digital pins, using 22 to 53. Can pins 0 to 13 and SCL1, SDA1 be used as digital inputs?

How about analog pins (A0 to A11) and DACs?

Thanks!


texts: Connect bluetooth module when no pins free

texts: I need do communicate atmega88 with a smartphone via bluetooth using a bluetooth HC-05 module. The problem is that all my atmega pins are being used. Rxd and txd pins are being used by a keypad (Keypad at PORTD). My project is almost done, at this stage i don't want to change the micro. Is there any alternative to solve this problem? Thanks


texts: How to use an Arduino along with a PPG sensor to find respiration rate

texts:
I am working on a project where I am trying to determine respiration rate through an Arduino Nano and a MikroE Heart Rate 3 Click device.  I have been working on this for a few months, reading different research papers attempting to find an algorithm that would give me respiration rate values, but am having trouble finding an algorithm that both does what I need and encode it into the Arduino.  Does anyone know of a code that would work?
I have so far have only the basic code that reads the PPG values, but it does not provide me with the Respiration rate values.  This is the code I have so far:
/*
 * AFE4404 Basic Read library example.
 * https://github.com/rakshithbk/AFE4404-Library
 *
 * On Arduino Uno -  | AFE4404 | Uno Pin
 *                   | I2C_Dat | A4
 *                   | I2C_Clk | A5
 * get_led_val() will return uint32_t values.
 *
 * Advanced - you can modify the sample period and other
 * parameters in the library files (refer AFE4404 datasheet)
 */

#include <Wire.h>
#include <AFE_connect.h>

AFE A;

void setup() {
  Serial.begin(115200);
  Serial.println("AFE4404 basic readings -\n");
  A.init();
}

void loop() {
  Serial.print("LED 1 Val = ");
  Serial.print(A.get_led1_val());
  Serial.print("\t LED 2 Val = ");
  Serial.print(A.get_led2_val());
  Serial.print("\t LED 3 Val = ");
  Serial.print(A.get_led3_val());
  Serial.println();
}


texts:
I'm using a heart rate sensor along with an Arduino for a project of mine. I have to determine whether the heartbeat is following a particular pattern (eg: when when heartbeat regularizes a lot after a period of increased or largely varying, I need to trigger an alarm to show that it has regularized).

Can anyone give me suggestions on how I can go about doing this? Are there any libraries or software for doing basic statistical analysis on data like this?


texts: Arduino analogWrite source code explanation

texts:
The source code for the analogWrite function looks like this:

void analogWrite(uint8_t pin, int val) {
    ...
    sbi(TCCRnA, COM0x);
    OCRnx = val;
    ...
}

Where n is which timer (0, 1, 2...) and x is which pin is controlled by that timer (A, B).

This doesn't make sense to me, because the ATmega328P datasheet says that the bits TCCRnA.WGM0[1:0], and TCCRnB.WGM0 need to be set up as well.

Datasheet

Obviously the above code works, but how, with the missing bit settings?


texts: I2C_graphical_LCD_display, fatal error: avr/pgmspace.h: No such file or directory

texts:
I have a problem with an ESP32 devkit V1 card. I'm trying to connect a WG12864A Winstar mod graphics display via the I2C MCP23017 adapter (RobotDyn), using Nick Gammon's I2C_graphical_LCD_display.h library.

Everything works well by connecting it to the Arduino Uno - Duemilanove board. Loading the sketch LCD_Demo_Using_I2C present in the library is compiled correctly without errors.

If I connect the display to ESP32 devkit V1, I try to compile it I get the following error:

C: \ Users \ Topolino \ Documents \ Arduino \ libraries \ I2C_graphical_LCD_display-master / I2C_graphical_LCD_display.h: 62: 26: fatal error: avr / pgmspace.h : No such file or directory.
Compilation terminated.
exit status 1
Error during compilation for DOIT ESP32 DEVKIT V1 card.

I tried to compile it with PlatformIO presents the usual compilation error.
You can help me, someone has some ideas to solve the problem.


texts: Too slow start up with Atmega2560 on custom PCB

texts:
I have some several custom PCB's based on Atmega 2560.
I am using AVRISP MarkII for flashing. No bootloader.

Flashing is flawless, it just works. I have one assembled PCB works as it should be, no issues.

But, the other one has a quite time lag in its functions.
It has also been flashed OK but, it is not running quite OK.

Here are my observations;

By asserting Reset, I expect four leds on the pcb running (on and then off) by 100ms intervals one after each others. This is happening in the very beginning in Setup() section of the program.

Note that: Leds are connected to MCU via mosfets. If MCU output is LOW, they are ON and vice versa.

So, with this problematic PCB, all leds come ON all together after 10 seconds after pressing reset button and they stay almost 60 seconds before they start the sequence (on and then off) as coded.

And then that sequence is also slowly occurring. It is not 100ms as I coded but almost 4 seconds or so.

I am suspecting from the external clock (16Mhz) circuitry but I can't proof it accurately as I don't have oscilloscope at hand.

You may see the simple code I use to test that behavior;

void TestLeds() {
    unsigned long interval = 100;

    digitalWrite(LED1_PIN, LOW);
    delay(interval);
    digitalWrite(LED1_PIN, HIGH);
    delay(interval);

    digitalWrite(LED2_PIN, LOW);
    delay(interval);
    digitalWrite(LED2_PIN, HIGH);
    delay(interval);

    digitalWrite(LED3_PIN, LOW);
    delay(interval);
    digitalWrite(LED3_PIN, HIGH);
    delay(interval);

    digitalWrite(LED4_PIN, LOW);
    delay(interval);
    digitalWrite(LED4_PIN, HIGH);
}

How/where should I check the bottle-neck on that?

Thank you.

EDIT:

To be more specific, I add this output regarding programming;
here


texts: Arduino Zero - Stepper control (interrupt)?

texts:
I have a stepper controller board that I need to pulse every 40 uS or so.

I also have I2C sensors and Serial writes to preform.

Currently I run an update call in a tight loop, but the I2C sensors and Serial writes cause considerable delays which makes the motors stutter and come to a halt.

I would like to use an ISR to call the motor update method periodically.

However I cannot for the life of me figure this timer stuff out.

Here's my current attempt:

void TC4_Handler() {
  Stepper::updateAll();
}

void setup() {

  // Timer stuff
  // Set up the generic clock (GCLK4) used to clock timers
  REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                    GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                     GCLK_GENCTRL_GENEN |         // Enable GCLK4
                     GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                     GCLK_GENCTRL_ID(4);          // Select GCLK4
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  // Feed GCLK4 to TC4 and TC5
  REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                     GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                     GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
  while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

  REG_TC4_COUNT16_CC0 = 0x000F;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

  //NVIC_DisableIRQ(TC4_IRQn);
  //NVIC_ClearPendingIRQ(TC4_IRQn);
  NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
  NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

  REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
  REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
  // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

  REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV1024 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                   TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                   TC_CTRLA_ENABLE;               // Enable TC4
  while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization
  // ...
}


texts:
I want to use the VCNL4000 Proximity/Light sensor s.
http://www.adafruit.com/products/466?&main_page=product_info&products_id=466

In the package i've this 6 pin connector but the VCNL has 5 pins (i now i can connect it by myself with male jumper) but  what am i missing here?
I assume that it is not an "accident" that the thing has one more pin then the sensor ; )


texts: Using USB or ethernet to carry digital signals

texts:
I need to send six digital signals about 4 feet through wires. An ethernet cable has 8 little wires that should do the trick. I could split the ends and solder them to my boards.

Is there an adaptor that will let me plug in the ethernet cable cable to my board and have access to the signal from each wire on a pin? If not, can I accomplish this through USB? Is there a more elegant solution than having six long wires?


texts:
In order to make an algorithm work, I'd like to delete the first line of a text file. I'm having a hard time finding an example for that though. I was thinking that there should be the possibility to delete up to a \n. Could you point me to a solution?
Oh, I'm using a standard Arduino Uno

Thank you


texts: Which sensor is best for obstacle detecting with retroreflector?

texts:
Distance is about 3m. IR or visible light - does not matter.

It is possible that object/obstacle can be shiny, so for correct detection necessary large amount of reflected light.

Maybe for this task better to use specific retroreflector?

UPDATE:

there will be two sensors with distance about 3-4 cm between.
Object must cross 1st sensor's reflector but do not cross the 2nd one.

The scheme of this sensor should be this:

But the use will be this:


texts: Turn on a LED when an other LED turn off

texts:
I'm a beginner on arduino.

I have an arduino mega with two LED (like the image with only 2 less and without the buzzer). A red LED and a green LED. When the arduino receive the code 200 I want the red LED turn on and the green LED turn off. But when I test that but any led turn off or turn on..

void setup()
{
  pinMode(LR, OUTPUT);
  pinMode(LV, OUTPUT);
  Serial.begin(9600);
}

void readSerial(){
  while(Serial.available() > 0){
    car = Serial.read();

    if(car != '+'){
      buff[i] = car;
      buff[i+1] = '\0';
      i++;
    }
    else{
      sscanf(buff, "%d", &received_code);
    }
  }
}

void loop()
{
  readSerial();
  if (received_code == 200){
    LRstate = HIGH;
    digitalWrite(LR, LRstate); // turn the LED on (HIGH is the voltage level)
    digitalWrite(LR,LOW);
    delay(100);
    digitalWrite(LV,LOW);
  }
}

How can I solve my problem?

Thanks a lot.


texts: Connecting 4 servos, 2 motors, hc-05, sr-04 and L293D to Arduino

texts:
I am trying to make an obstacle avoiding robot with robotic arm. First, I am from software programming field with no experience in electronics, circuits and Arduino. Using online tutorials so far I am able to blink an led, bluetooth communication between PC and Arduino and sonar range measurement.

After doing a lot of research on internet I have made the following diagram to connect  4 servos, 2 motors, hc-05, sr-04 and L293D to Arduino using "fritzing" software. I have the sketches for running servos and motors but I am not sure the circuit is correct due to the lack of knowledge in electronics. My doubts are,

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

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

The final robot will look like (I hope!) a "mearm" like robot arm attached on top of an obstacle avoiding robot.

UPDATED:


texts: Lowest voltage applicable on AREF pin on Uno and Mega

texts:
I need to measure an Analog signal in the range of 5-30 mV.

Naturally, using the internal default 5V reference leads to very poor measurement resolution. I would like to use the capability to use an external reference voltage of 50mV on the AREF pin (using an Agilent precision power supply)

However, when I tried this in the lab, I noticed something strange. The ADC readout on the channel remained stuck at 1023. If I used anything above 0.5V on the AREF pin, the readout on the ADC is correct, and the counts reliably go up and down when I ramp up and down the Analog input accordingly.

Any idea how to resolve my issue?


texts: Can't read two bytes through Serial.read - Arduino

texts:
I'm sending via Bluetooth with an Android App two bytes like this:

private void _sendCommand(byte command, byte arg)
{
    if (CONNECTED)
    {
        try
        {
            os.write(new byte[]{command, arg});
            os.flush();

        } catch (IOException e) {
            Log.e(TAG, "Error sending command: " + e.getMessage());

        }
    }
}

And this is the code I'm using to receive them with Arduino:

byte _instruction;
byte _arg;

void loop()
{
  while(Serial.available() < 2)
  {
    digitalWrite(LED_BUILTIN, HIGH);
  }

  digitalWrite(LED_BUILTIN, LOW);

  _instruction = Serial.read();
  _arg = Serial.read();
  Serial.flush();

  switch (_instruction)
  {

     ...

  }
}

I don't have any problems sending just one byte (modifying the code to receive just one), but I can't do the same with two bytes. It's always stuck in the while. Any idea of what I'm doing wrong?

EDIT: As ST2000 pointed out, there was a problem of syncronization, so this is the code working properly:

void loop()
{
  // Wait until instruction byte has been received.
  while (!Serial.available());
  // Instruction should be read. MSB is set to 1
  _instruction = (short) Serial.read();

  if (_instruction & 0x80)
  {
    // Wait until arg byte has been received.
    while (!Serial.available());
    // Read the argument.
    _arg = (short) Serial.read();

    switch (_instruction)
    {
      ...
    }
  }

  Serial.flush();
}

Thanks,


texts: Leonardo sketch and bootloader hex file combination

texts:
Can I combine Leonardo sketch hex file with the Leonardo bootloader hex file?
I would like to program blank Atmega32U4 with one shot.


texts: parse intel hex into SPI commands for arduino ICSP AVR

texts:
I'm attempting to use the arduino as an ICSP AVR to flash hundreds of ATMEGA's 90USB162.  I'm having some difficulties when trying to do the actual flashing of the chip.  I've go all the wires done properly and I'm able to read the signature.  My source is an Intel hex file and I'm reading it properly as I'm able to see each by as it is read from the arduino's memory.  Where I'm getting lost is the documentation states that I need to set the low byte first before I set the high byte for the same memory address.  Using the following as an example (underscores to break the data up) could someone help me descern what my SPI transaction bytes would look like?

:_20_0000_00_16C100003CC100003AC1000038C1000036C1000034C1000032C1000030C10000_48

I know the colon is the start code, 20 is the hex value of number of data bytes,  0000 is the address, 00 is the record type,  the next 32 bytes is my data followed by the checksum.

I thought that I would loop over the data portion and increment the address every other byte

uint16_t addr = 0;

while (recordtype != endOfFile)
{
  auto data[] = parseData();

  for(uint8_t index = 0; index < 32;)
  {
    SPITask.Send(0x40, 0x00, addr, data[index++]);//send low byte
    SPITask.Send(0x48, 0x00, addr, data[index++]);//send high byte
    SPITask.Send(0x4C, addr, addr, 0x00);//commit new bytes to address
    addr++;
  }
}

I don't think this is right and some examples i'm loosely following comment that they are changing the address byte into a word, which makes some sense based on the command layouts of the data sheet (page 260) 90USB162 Data sheet.  Can anyone please provide some guidance in how to break up this data into high and low bytes.


texts:
I was trying to get the timing in between events right, (Event time is around 150ms and i need it to be accurate within +-1ms) and came upon this implementation. The actual application will not be affected by the roll over, but would like to see if any of you guys (experts) can point out any flaws in using an empty while loop for time events, besides slightly higher power consumption.

This implementation gave me very accurate time spacings:

unsigned long previousMillis = millis();
Serial.print("ONE: ");
Serial.println(millis());
while(millis() - previousMillis < 1000);
Serial.print("SECOND: ");
Serial.println(millis());

compared with...

Serial.print("ONE: ");
Serial.println(millis());
delay(1000);
Serial.print("SECOND: ");
Serial.println(millis());

Which yields some errors after every step.


texts: Reading button presses with the 74HC4067E multiplexer

texts:
My project is progressing quite well, but I am having some issues reading button presses through my MUX.

The Goal

Cycle through twelve buttons and twelve LEDs. When a button is pressed, light up the corresponding LED. I have one MUX for the LEDs which is working great thanks to the stack exchange community. My button MUX is the issue.

The Symptom

I have one button hooked up to the MUX. When it is not pressed, nothing lights up - that's right. But when it is pressed, every LED lights up as it is cycled through. It is as if pressing this button for one of the MUX pins is sending a HIGH signal to all of the MUX pins.

The Pictures

^^ You can see the big honking button in the bottom right. It is connected to 5V and then the MUX pin.

^^ I have two multiplexers. The one on the left is for the LEDs and the one on the right is for the buttons (of which I currently [ha!] have only one).

The Code

// set vars for all the pins
int led_input = 0;
int led_ctrl_1 = 1;
int led_ctrl_2 = 2;
int led_ctrl_3 = 3;
int led_ctrl_4 = 4;

int btn_input = 5;
int btn_ctrl_1 = 6;
int btn_ctrl_2 = 7;
int btn_ctrl_3 = 8;
int btn_ctrl_4 = 9;

// how many MUX pins?
int players = 12;

// function to take player number and convert to control pins
void ledWrite(int led, boolean val){

    if(!val){

        digitalWrite(led_input, LOW);

    }else{

        if((led - 8) >= 0){
            led = led - 8;
            digitalWrite(led_ctrl_4, HIGH);
        }else{
            digitalWrite(led_ctrl_4, LOW);
        }

        if((led - 4) >= 0){
            led = led - 4;
            digitalWrite(led_ctrl_3, HIGH);
        }else{
            digitalWrite(led_ctrl_3, LOW);
        }

        if((led - 2) >= 0){
            led = led - 2;
            digitalWrite(led_ctrl_2, HIGH);
        }else{
            digitalWrite(led_ctrl_2, LOW);
        }

        if((led - 1) >= 0){
            led = led - 1;
            digitalWrite(led_ctrl_1, HIGH);
        }else{
            digitalWrite(led_ctrl_1, LOW);
        }

        digitalWrite(led_input, HIGH);
    }
}

// function to take player number and convert to control pins
int btnRead(int btn){

    if((btn - 8) >= 0){
        btn = btn - 8;
        digitalWrite(btn_ctrl_4, HIGH);
    }else{
        digitalWrite(btn_ctrl_4, LOW);
    }

    if((btn - 4) >= 0){
        btn = btn - 4;
        digitalWrite(btn_ctrl_3, HIGH);
    }else{
        digitalWrite(btn_ctrl_3, LOW);
    }

    if((btn - 2) >= 0){
        btn = btn - 2;
        digitalWrite(btn_ctrl_2, HIGH);
    }else{
        digitalWrite(btn_ctrl_2, LOW);
    }

    if((btn - 1) >= 0){
        btn = btn - 1;
        digitalWrite(btn_ctrl_1, HIGH);
    }else{
        digitalWrite(btn_ctrl_1, LOW);
    }

    return digitalRead(btn_input);
}

void setup(){

    pinMode(led_input, OUTPUT);
    pinMode(led_ctrl_1, OUTPUT);
    pinMode(led_ctrl_2, OUTPUT);
    pinMode(led_ctrl_3, OUTPUT);
    pinMode(led_ctrl_4, OUTPUT);
    pinMode(btn_input, INPUT);
    pinMode(btn_ctrl_1, OUTPUT);
    pinMode(btn_ctrl_2, OUTPUT);
    pinMode(btn_ctrl_3, OUTPUT);
    pinMode(btn_ctrl_4, OUTPUT);
}

void loop(){

    for(int x = 1; x <= players; x++){

        if(btnRead(x) == HIGH){

            ledWrite(x, true);
            delay(100);
            ledWrite(x, false);
        }
    }
}

I know this is a lot to trudge through, and I honestly appreciate any help you are willing to offer. Thanks in advance!


texts:
I am using a ESP8266, specifically the ESP-12-E :

I have a Relay, SRD-05VDC-SL-C connected to GPIO pin 4.
It is wired in Normally Open(with my device to be powered wired into the top and middle pins counting from the top to the bottom of the picture below):

In my arduino code when I issue:
  pinMode(4, OUTPUT);

This seems to pull the pin LOW, which is the active state of the relay, powering it, which turns my device on before my control code has even had chance to run. I want to get the pin for output but keep it floating.
How do I setup my pin for output, but leave it 'floating' from code, or keep it high / floating, so that I have to explicitly issue:
digitalWrite(4, LOW);

Before low is sent to activate my relay?
Hope this makes sense!


texts:
Simple question, of course if you do this

FunctionA();
Delay(1000);
FunctionB();
FunctionC();

it will call A, then wait a second, then call B, then call C.

How does one do this? ...

FunctionA();
.. Invoke FunctionX one second from now ..
FunctionB();
FunctionC();

So, I want it to do A, then without stopping continue to B and then C.  Later (one second later) it will do X.

Of course, in c# you'd just use a coroutine, in Android you'd use a Handler or whatever.

Surely there's a command along the lines of .. invoke in .. 2000 .. method.

Really sorry for the basic question, experts, I am damned if I can find this anywhere. Thanks!


texts: How can I store a value of 1000 over to EEPROM of Arduino Nano?

texts:
I need some of your feedback and guidance. In my prototype project powered by Arduino Nano(Space Constraint), it will operate continuously until it reach a maximum of 100 hours. Once it reached 100 hours mark, Nano will prompt users to do servicing/maintenance etc.
So in order to preserve the operating time from losing when powered off, I used EEPROM library to store the data. Based on my research, EEPROM.update(addr,value), each addr can hold one byte, which is 0-255 values. To prevent my EEPROM die from storing operating time of 100 hours, I used flag method, where every 5 mins of operation it will increase flag and store the flag value to EEPROM.
Is there other method other than changing the 5 mins benchmark?
Below is the simple/direct code that I wrote, the original code is too complex, and I have put a few comment especially the "Ideal Command" that I want.
#include <EEPROM.h>

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

  regenflag=EEPROM.read(regenaddr);
}

void loop()
{
regenflag=EEPROM.read(regenaddr);

if(totaltime>=300000)//Every 5min machine operated, increase regenflag (Fixed)
  {
    regenflag=regenflag+1;
    Serial.print("How many times it Operated==> ");
    Serial.println(regenflag);
    unblink=1;//Flag for other operation

    EEPROM.update(regenaddr,regenflag);
    regendata=EEPROM.read(regenaddr);

    totaltime=0;
}

/////////////////////////////////Ideal Command/////////////////////////////////////////////////////////
if (regendata>=1200) //100hrs=6000mins (6000mins/5mins=1200 times)
{
  Serial.println("Need to do Servicing")
}


texts: Power Arduino with 12V while using Serial Communication over USB

texts:
I'm going to build a 8x8x8 Led RGB Cube, therefore I will need a lot of Power which the arduino can't handle, so I'm using a 12V 20A (I know 20A isn't necessary but I had one laying around).

So the question is, is it possible to power the arduino over the Vin Pin with the 12V and program / communicate over serial connection in the same time? Like a real time programmed RGB LED Cube.

simulate this circuit – Schematic created using CircuitLab


texts:
I am trying to create a prototype for a nonprofit.

Basically the Arduino 101 board would be able to send an email/text when it senses movement. It is equipped with an accelerometer which could dictate when to send a message. A wifi board from Adafruit (CC3000) is used as a shield. Anyone know how that might be possible? Thanks in advance.

Status: Have been able to use Madgwick and CurieIMU libraries to visualise the output from the 101 using Programmer.

Trying to connect wifi shield at the moment...


texts: Can't get LCD(1602A v2) to communicate with AVR ATMEGA2560

texts:
I have written the following code to communicate with an LCD display yet I can  not get data to appear on the screen. All I get is white boxes on the display. I am properly controlling the RW, RS and Enable pins to my knowledge. I am using an ATmega2560 and an 1602A v2 LCD. And yes you can program the Atmega2560 in the atmel studio environment. Any advice from anyone???

Please help me here, I am desperate to learn what I am doing wrong. Thank you for everything everyone.

And for the oddly formatted code:

#include <avr/io.h>
#include <stdio.h>
#define F_CPU 16000000L
#include <util/delay.h>
#include "serial.c" //this allows me to use a serial monitor

//Pre-defining Commands
#define LCDClear 0x01 //Clears LCD Display,this is a command
#define LCD8bit 0x38 //Sets up LCD in 8bit mode
#define LCDSeek00 0x80 //Seeks the pointer to the beginning

#define LCD_E  PK1    // PORTK.1
#define LCD_RS PK3    //, RS for text
#define LCD_RW PK2   // PORTK.2, RW  is for commands
// Data and Busy flag are on P.....

void character(unsigned char ch);
void command(unsigned char ch);
void LCDInitialize(void);

int main()
{ DDRA=0xff; //the 8 data pins, setting pin a for output
    DDRK=0xff;  //this port used for Enable, RW, and RS
    PORTK=0xff;
    init_UART();//enables the USB's serial feedback from trouble shooting purposes

    printf("hello");

    _delay_ms(2000);
    LCDInitialize();
    printf("initialized");
    command(0x01);
    character("C");
    character("i");
    character("r");
    character("c");
    character("u");
    character("i");
    character("t");
    character("s");
    character(" ");
    character("T");
    character("o");
    character("d");
    character("a");
    character("y");
    return 0;
}
void character(unsigned char letter)
{ _delay_ms(20);
PORTK &=~(1<<LCD_RW);
PORTK |= ( 1<<LCD_RS|1<<LCD_E); //both RS and Enable must be high to

send data, enable will need to be taken low  however
DDRA=0xff;
PORTA=letter;
_delay_ms(20);
PORTK &=~(1<<LCD_E);//takes enable low
DDRA = 0;   // release bus

}
void command(unsigned char ch)
{
    PORTK &= ~(1<<LCD_RS);  //RS low for Command
    PORTK |= (1<<LCD_E);    //Enable pin high
    DDRA=0xff;
    PORTA = ch;         // put data on Port
    asm volatile ("nop");
    asm volatile ("nop");
    asm volatile ("nop");
    asm volatile ("nop");
    PORTK &= ~(1<<LCD_E);   //Enable Pin Low
    DDRA = 0;                // release bus

}
void LCDInitialize(void)
{

command(LCD8bit);
        _delay_ms(1);

command(0b00001111);//I believe this makes cursor blink, but didn't work for me

command(LCDClear);
    command(LCDSeek00);
}


texts: Does the map() function works on an ATtiny85?

texts:
I have a working project on Arduino Uno.Now I want to shrink my project using an ATtiny85. Before purchasing an waiting for the shipment to arrive, I want to make sure that my whole code will run on ATtiny85.

specialy, will the map() function which is working on  an Arduino Uno ( ATMEGA328P-PU ),  work with a ATtiny85 Microcontroller?


texts: I need my Arduino Due to work only from external power supply, not from USB power. Is there any way to modify the circuit to allow this? I still need to keep USB communication, but it should happen only when external power is on. Thanks


texts: Is there any way to use the serial port as an interruption source?

texts:
I have and sketch made for reading a temp/hum sensor once every ten seconds aprox. However, I want to introduce an interruption source to send from my keyboard a magic word to make the sensor be read exactly at that instant.

By checking out the reference on attachInterrupt(), I found only the ways to declare interrupt pins, but nothing related to serial. What you can say about it?

Thanks in advance.


texts:
Basically its an arduino project in which i am using an analog temperature sensor ky 013. The sensor is reading the temperatures correctly but what i want is to print the temperatures showed on the serial monitor to a lcd screen. I did the wiring and everything correctly  but there is something wrong with the code which i couldnt figure out.
Here is the code.

#include <math.h>

#include <LiquidCrystal.h>
LiquidCrystal lcd = LiquidCrystal(12, 11, 5, 4, 3, 2);

const int sensorPin = A0;
int switchState=0;

double Thermistor(int RawADC)
{
    double Temp;
    Temp = log(((10240000/RawADC) - 10000));
    Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
    Temp = Temp - 273.15;
    return Temp;
}

void setup()
{
    Serial.begin(9600);
    lcd.begin(16, 2);
    pinMode(sensorPin,INPUT);
}

void loop()
{

 switchState=digitalRead(sensorPin);
 int readVal=analogRead(sensorPin);
 double temp =  Thermistor(readVal);
 Serial.print("Temp. : ");
 Serial.print(temp);
 Serial.println(" Celsius");
 lcd.clear();
 lcd.setCursor(0,0);
 lcd.print("Temp: ");
 lcd.print(temp);
 lcd.print(" C");
 delay(500);
}


texts: IDE to program Arduino Uno especially internal interrupt vectors

texts:
I am trying to program this Arduino Uno's Timer1 module to use its Input Capture pin to record the times of edges and store / transmit them during the Input Capture Interupt Service Routine, but I cannot find documentation on how to program the guts of this Arduino Uno?

What IDE do people use to do advanced things with their Arduinos? I am trying to use Atmel Studio 6 after I gave up using the Arduino IDE and now I'm trying to use Visual Micro plug-in for visual studio.

Suggestions?


texts: I am very new to Arduino and the kit tutorial just told me to wire this, I do not know how to wire it. Can Someone plz help!

texts: I can't figure out how to do this the only wires I have are Jumper Wire and M-F 20 Pin DuPont Wire.


texts:
I recently started a project with HC-SR04 sensors and RTC DS1302 clock. The idea is when a sensor detects an object, call and keep a timestamp (hh:mm:ss) all over the loop until Else If{} appears,  but I don't know how to.

#include <DS1302.h>
#include <Time.h>
#include <TimeLib.h>
#define echoPin 12 // Echo Pin
#define trigPin 13 // Trigger Pin

time_t t = now();
DS1302 rtc(6,20,21);
String inTime;

void setup()
{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

   if (distance <= 4) {
    inTime= rtc.getTimeStr();
    Serial.println(inTime);

    }

    else if (distance >= 5 || distance <= 0){
    Serial.println("Out of range");

    }

  delay(500);
}

Appreciate any help, thanks.


texts: How to determine hardware/software compatibility?

texts:
Currently, I'm using Greiman's SdFat Library with Adafruit's Data logging Shield.

I'm thinking about switching to the Adafruit micro SD Card Breakout. I imagine that it will work as both products are made by Adafruit, and the board schematics look similar. However, I don't know what to look at to be sure they are the same.

Is it enough that they both use the HC4050M chip, or is there something else that I need to be aware of?

Short of buying one and testing it. What do I need to look at to verify that these two boards will work with the library?


texts: What is the maximum length an Interrupt Service Routine?

texts:
In general, what's the maximum length of instructions that can be included in an Interrupt Service Routine?

The docs say an ISR should be "as short and fast as possible", but that's bit vague.

For example, I have an ISR that gets called for each pulse on an motor's encoder.

void on_encoder_pulse(){
    encoder_change = true;
    count1 += 1;
    count2 += last_call;
    last_call = millis();
}

Will this run without interruption?


texts: Lilygo TTGO T-Beam Guru Meditation Error

texts:
I have recently purchased a lilygo ttgo t-beam (868Mhz version) on which I try to run the "DeviceInfo" example code provided by TheThingsNetwork. When executing ttn.ShowStatus(); I see in the Serial Monitor an error stating that "core 1 panic'ed" and the device keeps rebooting eternally.
I am new to this but I think I have not missed any steps. I have included the "TheThingsNetwork" library successfully (the sketch compiles when I include it) and I have added some Additional Boards Manager URLs to help Arduino IDE find my board.
So far,
I have added these links to the Additional Boards Manager URLs:
http://downloads.sodaq.net/package_sodaq_index.json,
http://downloads.sodaq.net/package_sodaq_samd_index.json,
https://dl.espressif.com/dl/package_esp32_index.json,
https://raw.githubusercontent.com/Lauszus/Sanguino/master/package_lauszus_sanguino_index.json,
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
And I select T-BEAM board.
My sketch is this:
#include <TheThingsNetwork.h>

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan TTN_FP_EU868

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);
}

void loop()
{
  debugSerial.println("Device Information");
  debugSerial.println();
  ttn.showStatus();
  debugSerial.println();
  debugSerial.println("Use the EUI to register the device for OTAA");
  debugSerial.println("-------------------------------------------");
  debugSerial.println();

  delay(10000);
}

and this is the error message I get on debugSerial:

In my understanding this is either a problem with the board I select (TBeam) or a possible but on TheThingsNetwork library.
I would appreciate some help to run this script successfully so I can register my device on TheThingsNetworkor, or at least debug further this problem.
Thank you in advance.


texts: Adafruit Feather ESP32 - GPIO power drain during deep sleep

texts:
I have an Adafruit Feather ESP32 whose GPIOs I use to control an external device. I don't want the device to drain the power of the ESP32 sometimes, so I set the GPIOs to INPUT. When I go into deep sleep though, the GPIOs suddenly get some random voltages and start drawing power. A few GPIOs are 3.3V, others are 0.7V, and some are near 0V.

What is the correct/standard way to make the microcontroller not leak any power to that external device.
One way is obviously physically disconnecting that device, but I want an automated way. Is it solvable by software or do I need special hardware to achieve my goal?


texts: The exact time for functions or CPU cycles for any function

texts:
I'm trying to read input data from the parallel port of a PC and send it to another device. For this purpose the input data is saved, when it's available and is sent if a flag is set.

The whole procedure should be done in less than 10 ms. I need to know the running time. How can I compute the CPU cycles for ReadParallel and WriteParallel functions (digitalRead, digitalWrite, bitRead,bitWrite) in my code or any other instructions?

Here is the code for the Arduino Uno:

#define InterruptInputPin 2 // For checking if the input data is available
#define InterruptSensorPin 3 // For checking when to send data

#define IN0 A0
#define IN1 A1
#define IN2 A2
#define IN3 A3

#define OUT0 5
#define OUT1 6
#define OUT2 7
#define OUT3 8

volatile int ParallelInput; // The input data

//*************************************
void ReadParallel() //Reads input and saves it in parallelInput.
{
  if (digitalRead(IN0) == HIGH)
    bitWrite(ParallelInput,0,1);
    else
      bitWrite(ParallelInput,0,0);

  if (digitalRead(IN1) == HIGH)
    bitWrite(ParallelInput,1,1);
    else
      bitWrite(ParallelInput,1,0);

  if (digitalRead(IN2) == HIGH)
    bitWrite(ParallelInput,2,1);
    else
      bitWrite(ParallelInput,2,0);

  if (digitalRead(IN3) == HIGH)
    bitWrite(ParallelInput,3,1);
    else
      bitWrite(ParallelInput,3,0);

}
//***************************************

void WriteParallel() //Writes ParallelInput to output.
{
  detachInterrupt(digitalPinToInterrupt(InterruptInputPin));
  digitalWrite(OUT0,bitRead(ParallelInput,0));
  digitalWrite(OUT1,bitRead(ParallelInput,1));
  digitalWrite(OUT2,bitRead(ParallelInput,2));
  digitalWrite(OUT3,bitRead(ParallelInput,3));
  attachInterrupt(digitalPinToInterrupt(InterruptInputPin),ReadParallel,RISING);

}

void setup() {

  pinMode(IN0,INPUT);
  pinMode(IN1,INPUT);
  pinMode(IN2,INPUT);
  pinMode(IN3,INPUT);

  pinMode(OUT0,OUTPUT);
  pinMode(OUT1,OUTPUT);
  pinMode(OUT2,OUTPUT);
  pinMode(OUT3,OUTPUT);
  attachInterrupt(digitalPinToInterrupt(InterruptInputPin),ReadParallel,RISING);

attachInterrupt(digitalPinToInterrupt(InterruptSensorPin),WriteParallel,RISING);

}

void loop() {

}


texts: Array variable name changes from readings1 to readings2

texts:
I've been using two MB1240 Ultrasonic Sensors with analogRead, and have found that after using bubble sort, the array is found in array readings2, and not readings1. This is important because I would like to find the distance from each sensor.

Below is the code I've put together that uses buttons to determine when each sensor should be triggered.

const int anPin1 = 1;
const int anPin2 = 2;

const int triggerPin = 2;
long anVolt1, anVolt2;

// button Pins
const int buttonPin1 = 11;
const int buttonPin2 = 13;

int buttonState1;
int buttonState2;
int lastButtonState1 = false;
int lastButtonState2 = false;

long lastDebounceTime1 = 0;
long lastDebounceTime2 = 0;
long debounceDelay = 50; //ms

// initialise averaging array
const int numberOfReadings = 10; // reasonable DOF
long readings1[numberOfReadings];
long readings2[numberOfReadings];
long median;

void setup() {
  Serial.begin(9600);
  pinMode(triggerPin,OUTPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  delay(200); // Datasheet: Sensors require 175 ms to calibrate
}

void start_sensor(){
  digitalWrite(triggerPin,HIGH);
  delay(10);
  digitalWrite(triggerPin,LOW);
}

long read_sensor1(){
  //Used to read in the analog voltage output that is being sent by the XL-MaxSonar device.
  //Scale factor is (Vcc/1024) per centimeter. A 5V supply yields ~4.9mV/cm for standard range sensors
  anVolt1 = analogRead(anPin1);
  return anVolt1;
}

long read_sensor2(){
  anVolt2 = analogRead(anPin2);
  return anVolt2;
}

void printall(long readings[]) {
  int med = numberOfReadings/2;
  median = (readings[med-1] + readings[med])/2;

  Serial.print("Sensor: ");
  for (int i = 0; i < numberOfReadings; i++) {
    Serial.print(readings[i]);
    Serial.print("cm ");
  }
  Serial.println();

  Serial.print("Median: ");
  Serial.print(median);
  Serial.println(" cm");
}

void loop () {
  int reading1 = digitalRead(buttonPin1);
  int reading2 = digitalRead(buttonPin2);

  // for noise
  if (reading1 != lastButtonState1) {
    lastDebounceTime1 = millis();
  }

  // for noise
  if (reading2 != lastButtonState2) {
    lastDebounceTime2 = millis();
  }

  if ((millis() - lastDebounceTime1) > debounceDelay) {
    if (reading1 != buttonState1) {
      buttonState1 = reading1;
      if (buttonState1 == HIGH) {
        for (int i = 0; i < numberOfReadings; i++){
         start_sensor();
          readings1[i] = read_sensor1();
          delay(150); // From datasheet: Period = 99ms
        }

            **// bubble sort with flag
        for (int i = 0; i < sizeof(readings1)-1; i++) {
            bool flag = true;
            for (int j = 1; j < sizeof(readings1)-1; j++) {
                if (readings1[j-1] > readings1[j]) {
                    int t = readings1[j-1];
                    readings1[j-1] = readings1[j];
                    readings1[j] = t;
                    flag = false;
                }
            }
            if (flag) break;
        }
       printall(readings1);**
      }
    }
  }

  lastButtonState1 = reading1;

  if ((millis() - lastDebounceTime2) > debounceDelay) {
    if (reading2 != buttonState2) {
      buttonState2 = reading2;
      if (buttonState2 == HIGH) {
        for (int i = 0; i < numberOfReadings; i++) {
          start_sensor();
          readings2[i] = read_sensor2();
          delay(150);
        }
       printall(readings2);
      }
    }
  }
  lastButtonState2 = reading2;

  //clear previous readings
  memset(readings1, 0, sizeof(readings1));
  memset(readings2, 0, sizeof(readings2));
}

Scenario: I have clicked the first button to return a reading from the first sensor, and I am expecting the results to be stored then sorted in array readings1. After the bubble sort, if I enter printall(readings1), it returns an array of zeros, but if I use a printall(readings2), it returns the sorted array I expected.

I can't find where I'm going wrong with this one, any help would be greatly appreciated. Thank you!


texts:
Context

I am building a small battery powered counting device. As with many other projects like this, saving power is critical. I am therefore trying to utilise the sleep mode wherever possible. This is using a 328P as a standalone MCU running on the 1MHz internal clock

The Hall Effect sensor I am using outputs Vcc when nothing is detected, and Ground when something is detected. It therefore seems well suited to being used as a trigger for an interrupt to wake up the 328P from sleep (so that I don't even need to use a watchdog timer.)

Below is an excerpt from my code. This code does put the processor into sleep as desired. However, from testing I have discovered that the device will not sleep when the magnet is left near the sensor, as its output stays LOW. As I only want to detect pulses of a moving piece of metal, this is wasting power. I only want to wake up when it is initially detected on each cycle.

void sleepLoop()
{
  Serial.print("S");

  delay(5);   //scales to 40ms

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  noInterrupts();

  attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, LOW);

  interrupts();
  sleep_cpu();

  //The program will continue from here.

  //First thing to do is disable sleep.
  sleep_disable();
}

I therefore changed

attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, LOW);

to

attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, FALLING);

PROBLEM

Now my processor never goes to sleep. For debugging I have put in a serial print at the start of the loop so that I know it has entered this loop of code. Whether LOW or FALLING is used the 'S' is printed. I only know it is not sleeping because I am measuring the current flow.

I thought the sensor may be going LOW long enough to keep the device awake, but not long enough to register as a count (as I have a debounce in there) so I have checked the output from the sensor with an oscilloscope in case it was momentarily going LOW, but I couldn't see any sign of this.

The findings from the oscilloscope make me feel like there is something about the interrupt function that I am overlooking. Any help would be greatly appreciated!


texts:
I have this code C code that compiles OK on my laptop

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

unsigned int crc32(const void *m, size_t len) {
  const unsigned char *message = m;
  size_t i;
  int j;
  unsigned int byte, crc, mask;

  i = 0;
  crc = 0xFFFFFFFF;
  while (i < len) {
    byte = message[i];
    crc = crc ^ byte;
    for (j = 7; j >= 0; j--) {
      mask = -(crc & 1);
      crc = (crc >> 1) ^ (0xEDB88320 & mask);
    }
    i = i + 1;
  }
  return ~crc;
}

int main() {
  char str[] =
      "620004";
  size_t len = strlen(str);
  unsigned int crc = crc32(str, len);

  size_t len2 = (len + 1) / 2;
  unsigned char arr2[len2];
  for (size_t i = 0; i < len; i += 2) {
    arr2[i / 2] = strtoul((char[3]) {str[i], str[i + 1], '\0'}, 0, 16);
  }
  crc = crc32(arr2, len2);
  printf("CRC: 0x%X\n", crc);

  return 0;
}

And I'm trying to port it to Arduino

#include <CRC32.h>

void setup() {
  Serial.begin(115200);
  uint8_t byteBuffer[] = "620004";
  size_t numBytes = sizeof(byteBuffer) - 1;
  size_t len2 = (numBytes + 1) / 2;
  unsigned char arr2[len2];
  CRC32 crc;
  for (size_t i = 0; i < numBytes; i += 2) {
    arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
  }
  for (size_t i = 0; i < numBytes; i++){
    crc.update(byteBuffer[i]);
  }

  uint32_t checksum = crc.finalize();
  Serial.print("CRC: ");
  Serial

But I'm getting a

Arduino: 1.8.9 (Linux), Board: "Arduino/Genuino Uno"

/home/nico/Arduino/crc32/crc32.ino: In function 'void setup()':
/home/nico/Arduino/crc32/crc32.ino:11:50: warning: narrowing conversion of 'byteBuffer[i]' from 'uint8_t {aka unsigned char}' to 'char' inside { } [-Wnarrowing]
     arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
                                                  ^
/home/nico/Arduino/crc32/crc32.ino:11:69: warning: narrowing conversion of 'byteBuffer[(i + 1u)]' from 'uint8_t {aka unsigned char}' to 'char' inside { } [-Wnarrowing]
     arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
                                                                     ^
crc32:11:84: error: taking address of temporary array
     arr2[i / 2] = strtoul((char[3]) {byteBuffer[i], byteBuffer[i + 1], '\0'}, 0, 16);
                                                                                ^
exit status 1
taking address of temporary array

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

And I'm not really understanding what's the issue here with the strtoul function and its different behavior on Arduino


texts: How to work with non-traditional UART baud rates

texts:
I am trying, unsuccessfully to communicate, using my Arduino Nano, with a custom device at a baud rate of 800 kbit/s.

The Arduino code look like this:

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

void loop() {
  // Put your main code here, to run repeatedly:
  delay(5000);
  Serial.println(0x2be1);
}

When I am trying to debug it with PuTTY the result is:

And when I change the baud rate to 400 kbit/s the result is (as it should be):

Any idea?


texts: For a class assignment I have been tasked with zeroing a Vernier force probe by typing a command into the serial monitor. I am having trouble writing the code for this algorithim. I was hoping to give the monitor the command and have it save the analogread as a variable which I can later subtract from future reads. Does anyone know if I can save the analogread value without it being updated in a loop? If, so how?


texts: Simple question about the SPI clock for Intel Edison

texts:
I am doing a project with an Intel Edison Arduino breakout board.

http://store.arduino.cc/product/E000052

http://download.intel.com/support/edison/sb/edisonmodule_hg_331189002.pdf

I have a device that I want to communicate with by SPI.  This device can receive a maximum of 16MHz for its clock.  I want this maximum speed of 16 MHz.  From what I understand, the Edison can output a clock speed of 19.2 MHz.

I don't know much about clocks and I am still learning.  Is it possible to program the Edison to operate its SPI output clock at a speed of 16 MHz?  If so, how would this be done?


texts: Cannot access "tools>Serial port" on Kali Linux

texts:
I just got my Arduino UNO delivered and I wanted to see if it's working properly or not.

I tried following this page to create a simple program and the program compiled successfully.

But when I tried to select the serial port on IDE, the port option was grayed out. I searched for the problem and I landed on this page. It says

  Linux includes the drivers necessary to use Arduino, and no additional
  install is needed. However, permissions might need to be configured.
  For current instructions on how to set up these permissions, visit
  this page.

  An alternative method is to run Arduino as root in the terminal.

But I still see the port option grayed out even as a root user. Any idea?


texts:
Code

/*Arduino Bluetooth Controlled Car
 *  * Created by Glen Tech
 * https://www.youtube.com/glentech
  */

#include <AFMotor.h>

//initial motors pin
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor3(3);
AF_DCMotor motor4(4);

char command;

void setup()
{
  Serial.begin(9600);  //Set the baud rate to your Bluetooth module.
}

void loop(){
  if(Serial.available() > 0){
    command = Serial.read();
    Stop(); //initialize with motors stoped
    //Change pin mode only if new command is different from previous.
    //Serial.println(command);
    switch(command){
    case 'F':
      forward();
      break;
    case 'B':
       back();
      break;
    case 'L':
      left();
      break;
    case 'R':
      right();
      break;
    }
  }
}

void forward()
{
  motor1.setSpeed(1000); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor2.setSpeed(1000); //Define maximum velocity
  motor2.run(FORWARD); //rotate the motor clockwise
  motor3.setSpeed(1000);//Define maximum velocity
  motor3.run(FORWARD); //rotate the motor clockwise
  motor4.setSpeed(1000);//Define maximum velocity
  motor4.run(FORWARD); //rotate the motor clockwise
}

void back()
{
  motor1.setSpeed(1000); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor2.setSpeed(1000); //Define maximum velocity
  motor2.run(BACKWARD); //rotate the motor anti-clockwise
  motor3.setSpeed(1000); //Define maximum velocity
  motor3.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(1000); //Define maximum velocity
  motor4.run(BACKWARD); //rotate the motor anti-clockwise
}

void left()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor2.setSpeed(255); //Define maximum velocity
  motor2.run(BACKWARD); //rotate the motor anti-clockwise
  motor3.setSpeed(255); //Define maximum velocity
  motor3.run(FORWARD);  //rotate the motor clockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(FORWARD);  //rotate the motor clockwise
}

void right()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(FORWARD); //rotate the motor clockwise
  motor2.setSpeed(255); //Define maximum velocity
  motor2.run(FORWARD); //rotate the motor clockwise
  motor3.setSpeed(255); //Define maximum velocity
  motor3.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(255); //Define maximum velocity
  motor4.run(BACKWARD); //rotate the motor anti-clockwise
}

void Stop()
{
  motor1.setSpeed(0); //Define minimum velocity
  motor1.run(RELEASE); //stop the motor when release the button
  motor2.setSpeed(0); //Define minimum velocity
  motor2.run(RELEASE); //rotate the motor clockwise
  motor3.setSpeed(0); //Define minimum velocity
  motor3.run(RELEASE); //stop the motor when release the button
  motor4.setSpeed(0); //Define minimum velocity
  motor4.run(RELEASE); //stop the motor when release the button
}


texts: Why does my servo twitch and turn on its own?

texts:
I've been trying to write a very simple program using Arduino to tell a servo to go to a specific angle when a button is pressed, and to another specific angle when it is released. I find that, even though my sketch is but the simplest possible if then else statement without anything added to it, the servo goes to the right angle when the button is pressed, but when it is released, the servo oscillates between the two specified angles at a regular rate (about once every second). What's even stranger is that when i add delay time to the end of the loop in my sketch, the oscillation becomes more like twitching, and the more delay i add the weirder and less predictable the twitching becomes.

added info

#include <Servo.h>
Servo Servo1;
int const switchPin = 4;
int switchState = 0;
void setup()
{
    Servo1.attach(11);
}

void loop()
{
    switchState = digitalRead(switchPin);
    if (switchState == HIGH) {
        Servo1.write(40);
    } else {
        Servo1.write(70);
        delay(39);
    }
}

the power supply is the regular usb connector plugged from the board to my computer. The circuit is virtually similar to the "mood cue" project on the arduino projects book, except there is a button connected to digital pin 4 instead of a potentiometer.


texts:
I found this example on how to create a project with AUnit tests: https://www.thecoderscorner.com/electronics/microcontrollers/embedded-testing/getting-started-unittesting-arduino/
According to it and projects I have found on github my project structure should look like this:
Application
    src
        SomeComponent.cpp
        SomeComponent.h
    tests
        TestSomeComponent
            TestSomeComponent.ino
    Application.ino

But when I try to run TestSomeComponent.ino with Arduino IDE or VSC with Arduino plugin it does not see contents of src folder. I am assuming that it is treated as a separate sketch. What is a proper way to build and run tests?
[edit]
Some context (not sure what matters):

Our target board is ESP32 DevKit v1
Optimally if our developers could run tests on Windows and Linux machines
I have not gotten yet to continuous integration. I will start automating once I have any test building and running

[edit 2]
I have tried command line tools. Got AUniter running and tried like this (hoping for some automagic done by tools):
me@mypc:~/workspace/Application/Application/tests$ auniter.sh test esp32:/dev/ttyUSB0 TestSomeComponent/

I have tried any sane path combination in include path directive, for example:
#include "SomeComponent.h"
#include "app/SomeComponent.h"
#include "../../src/app/SomeComponent.h"
#include <SomeComponent.h>
#include <app/SomeComponent.h>
#include <../../src/app/SomeComponent.h>

But I keep getting this:
TestSomeComponent:4:42: fatal error: ../../src/app/SomeComponent.h: No such file or directory


texts: Controlling Servo Motors with push button. Problem though

texts:
I have this setup where I have and Arduino Uno, a mini servo motor, and a pushbutton. I use a single pushbutton to control the servo motor to go to one position, then push it again to go back. It first goes to 0 degrees, then if you push it it goes to 180 degrees then vice versa. The problem is that in its initial state (which is 0 degrees), the servo motor makes noise. Like it's running or something then it gets hot.

I've seen other servo motors that never do this. Here is my code by the way:

#include <Servo.h>

const int buttonPin = 8;
const int servoPin = 9;
int buttonState = 0;
int directionState = 0;
Servo servoOne;
int pos = 0;

void setup() {
  servoOne.attach(9);
  servoOne.write(directionState);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (directionState == 0) {
    if (buttonState == HIGH) {
      directionState = 1;
      for (pos = 0; pos < 180; pos = pos + 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  } else if (directionState == 1) {
    if (buttonState == HIGH) {
      directionState = 0;
      for (pos = 180; pos > 1; pos = pos - 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  }
}

I really need all the help I can get.


texts:
My target is to use multiple MPU-6050 at once, I searched on the internet and found that they can be hooked up really simply. Just connect in parallel and use I2C-Scanner. Then get those addresses and use normally.

But I can't find another address, there appears to be just one address 0x68, that is the reason why, I want to connect my other MPU-6050 in other pins.

How this can be achieved ?


texts: How to use 503 Thermistors for temperature?

texts:
I have a black Thermistor with the number 503 on it.

I know that I would need a 50k resistor as a voltage divider.

I don't get to convert the number I am getting. I get the number 340 when my house is at 64*F.
I bought a kit on Amazon and it came with it and there is no documentation.A test with multimeter has shown at 17*C I get 30k ohms.

This is how it is wired:

[Ground] -- [50k-resistor] -- | -- [(503)thermistor] --[Vcc (5v)]
                              |
                         Analog Pin 0


texts:
I am looking for the arduino code to stream video to a webpage using the ESP8266.
here is the 4 wire camera I have: https://www.ebay.com/itm/172272466793

The other tutorials I'm finding online are all for a different cameras or are not using the ESP8266 for webpage streaming.

Any help or pointers would be most appreciated.

As a side note I have LiFePo 3.3v batteries that I plan to use to power both the ESP8266 and the 5v camera (by wiring them in series).
The thing I am completely lost on is how to wire the video and audio to ports and access them with arduino code.


texts:
I wrote the following code that outputs a packet data structure bit by bit.

I do this using two for loops. These two for loops should always terminate, but the presence of analogWrite() makes them not terminate.

More concretely:

#define PACKET_SIZE 2
#define NUM_BITS 8

#define LOGICAL_LOW 127
#define LOGICAL_HIGH 255
#define LOGICAL_NULL 0

#define DATA_OUT_PIN 13
#define DATA_IN_PIN 3

#define DELAY 200

struct packet {
  byte content[PACKET_SIZE];
  byte checksum;
};
void testFun(struct packet *p) {
  for (int i = 0; i < PACKET_SIZE; i++) {
    byte m = 1;
    for (int j = 0; j < NUM_BITS; j++) {
      Serial.println(i);
      if ((p->content[i] & m) == m) {
        analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
      }
      else {
        analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
      }
      m <<= 1;
    }
    Serial.println(i);
  }
  Serial.println("Other loop");
  for (int i = 0; i < NUM_BITS; i++) {
    byte m = 1;
    if ((p->checksum & m) == m) {
      analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
    }
    else {
      analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
    }
    Serial.println(i);
  }
  analogWrite(DATA_OUT_PIN, LOGICAL_NULL);
}
void setup() {
  Serial.begin(115200);
  pinMode(DATA_OUT_PIN, OUTPUT);
  pinMode(DATA_IN_PIN, INPUT);

  struct packet p;
  p.content[0] = 127;
  p.content[1] = 98;

  delay(3000);
  testFun(&p);

}

loops forever but this one doesn't:

#define PACKET_SIZE 2
#define NUM_BITS 8

#define LOGICAL_LOW 127
#define LOGICAL_HIGH 255
#define LOGICAL_NULL 0

#define DATA_OUT_PIN 13
#define DATA_IN_PIN 3

#define DELAY 200

struct packet {
  byte content[PACKET_SIZE];
  byte checksum;
};
void testFun(struct packet *p) {
  for (int i = 0; i < PACKET_SIZE; i++) {
    byte m = 1;
    for (int j = 0; j < NUM_BITS; j++) {
      Serial.println(i);
      if ((p->content[i] & m) == m) {
        analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
      }
      else {
        analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
      }
      m <<= 1;
    }
    Serial.println(i);
  }
  Serial.println("Other loop");
  for (int i = 0; i < NUM_BITS; i++) {
    byte m = 1;
    if ((p->checksum & m) == m) {
      analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
    }
    else {
      //analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
    }
    Serial.println(i);
  }
  analogWrite(DATA_OUT_PIN, LOGICAL_NULL);
}
void setup() {
  Serial.begin(115200);
  pinMode(DATA_OUT_PIN, OUTPUT);
  pinMode(DATA_IN_PIN, INPUT);

  struct packet p;
  p.content[0] = 127;
  p.content[1] = 98;

  delay(3000);
  testFun(&p);

}

the difference between these two being a single commented line in testFun

My entire sketch is as follows:

#define PACKET_SIZE 2
#define NUM_BITS 8

#define LOGICAL_LOW 127
#define LOGICAL_HIGH 255
#define LOGICAL_NULL 0

#define DATA_OUT_PIN 13
#define DATA_IN_PIN 3

#define DELAY 200

struct packet {
  byte content[PACKET_SIZE];
  byte checksum;
};
void testFun(struct packet *p) {
  for (int i = 0; i < PACKET_SIZE; i++) {
    byte m = 1;
    for (int j = 0; j < NUM_BITS; j++) {
      Serial.println(i);
      if ((p->content[i] & m) == m) {
        analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
      }
      else {
        analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
      }
      m <<= 1;
    }
    Serial.println(i);
  }
  Serial.println("Other loop");
  for (int i = 0; i < NUM_BITS; i++) {
    byte m = 1;
    if ((p->checksum & m) == m) {
      analogWrite(DATA_OUT_PIN, LOGICAL_HIGH);
    }
    else {
      analogWrite(DATA_OUT_PIN, LOGICAL_LOW);
    }
    Serial.println(i);
  }
  analogWrite(DATA_OUT_PIN, LOGICAL_NULL);
}

void setup() {
  Serial.begin(115200);
  pinMode(DATA_OUT_PIN, OUTPUT);
  pinMode(DATA_IN_PIN, INPUT);

  struct packet p;
  p.content[0] = 127;
  p.content[1] = 98;

  delay(3000);
  testFun(&p);

}

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

}

and its two outputs are
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
Other loop
0
1
2
3
4
5
6
7

and

0
0
0
...


texts: Using a 48 characters char[] for PROGMEM

texts:
I am trying to create a charliplexed display of 6x8 LEDS using a Arduino Nano with the ATMega328p chip. Because of the limited storage I am trying to use PROGMEM. I did my research and found some usefull examples, but when I try to create a char[] of 48 charaters (0 = LED off, 1 = LED on), the monitor only shows a line filled with squares. Im not sure what this indicates, but when I limit the amount of characters to lets say 10, it works as expected. I made sure the buffer size matches the amount of max characters. What am I missing here?

I know it would be easier to use a multiplexer, but I prefer to find a working solution using progmem since this is a assignment where I would like to have my students find a solution to store the "LED data" for the whole alphabet without using external memory or a multiplexer chip. If this simply is not possible, I will look into using other hardware.

TIA!

This is the code I am using:

#include <avr/pgmspace.h>
const char string_0[] PROGMEM = "000000000000000000000000000000000000000000000000"; // "String 0" etc are strings to store - change to suit.
const char string_1[] PROGMEM = "String 1";
const char string_2[] PROGMEM = "String 2";
const char string_3[] PROGMEM = "String 3";
const char string_4[] PROGMEM = "String 4";
const char string_5[] PROGMEM = "String 5";

// Then set up a table to refer to your strings.

const char *const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};

char buffer[48];  // make sure this is large enough for the largest string it must hold

void setup() {
  Serial.begin(9600);
  while (!Serial);  // wait for serial port to connect. Needed for native USB
  Serial.println("OK");
}

void loop() {
  /* Using the string table in program memory requires the use of special functions to retrieve the data.
     The strcpy_P function copies a string from program space to a string in RAM ("buffer").
     Make sure your receiving string in RAM  is large enough to hold whatever
     you are retrieving from program space. */

  for (int i = 0; i < 6; i++) {
    strcpy_P(buffer, (char *)pgm_read_word(&(string_table[i])));  // Necessary casts and dereferencing, just copy.
    Serial.println(buffer);
    delay(500);


texts: connecting a small motor to arduino using a transistor

texts:
I want to connect a small motor (water pump) to an arduino, and I am not sure about the circuit.
The pump is small, works with 3.3V, but consumes 0.1A so I decided to use a transistor. The one I have is BF547, an NPN type small transistor. It supports currents up to 100 mA.
I measured the hfe (beta) of the transistor, and it is 370. The Vcc is 3.3V, and the current through the motor is 0.1 A, therefore:
A. the Ib equals to Ic/hfe = 0.1A/370 giving Ib = 0,00027A
B. with the Vb at 3.3V(pin voltage) and Vbe at 0.7 (datasheet) the Rb = (Vb-Vbe)/Ib = 9558 Ohm (10kOhm)
My questions are:

Did I calculate the base resistance correctly?
Do I need any additional resistor for the collector, next to the pump? Is it possible that more current flows through the collector-emitter?
According to the datasheet of BF457 100mA is the max Ic it can take. Should I limit the pump by adding a small (10 Ohm) resistor to it (33 Ohm[motors resitance] + 10 Ohm for 3.3 V gives a current of 76 mA)

I am attaching the schematics (linear voltage regulator is there only to stabilise the Vcc provided by an old dc power source I found)
Thanks a lot for any suggestions!


texts: Triggering a Sleep Wake-up Event using analog output from a triple axis accelerometer?

texts:
I am working on a project that uses a Arduino MKR GSM 1400 and a ADXL335 Accelerometer . I am having trouble setting a interrupt wake up event on one of the GSM's interrupt-capable pin due to the analog nature of the ADXL335's output. The axis outputs typically range between ~1.4V-~2.2V with ~1.65V being the resting voltage level.
I have tried using a NTE987 op-amp to amplify the analog output enough to trigger a CHANGE on the interrupt pin I'm using. This resulted in the analog signal outputted by the ADXL335 boosting to a certain voltage level and not varying at all with any motion.
My current solution, which works very well but is not ideal for power consumption reasons, is using a smaller micro controller with less power draw's ADC to interpret the ADXL335's output and send digital wake-up signals to the GSM when certain thresholds are met. I would like to know if there's a better way to do this, as using an additional microcontroller to wake up the original microcontroller feels like a kludge.


texts: Why do random characters fill up my Arduino LCD Display?

texts:
I am making a water pump system for plants and I am running into trouble with displaying my Temperature and Humidity values. I am using a 20x4 LCD, Arduino board uno, Capacitive soil moisture sensor, 5v DC water pump, DHT22, and a single relay. When the motor is on, the display first shows the values as expected. Then, all of a sudden random characters fill and move across my screen. When I don't connect my motor to the Arduino, the values show up on the LCD as expected. Please do leave comments so that I am able to improve my code. Thanks.

//Libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "DHT.h"

//Pins Used
#define DHTpin 2
#define DHTtype DHT22

//Initialization
DHT dht(DHTpin, DHTtype);
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

int sensor_pin = 0; // Soil Sensor input at Analog PIN A0
int pinValue;
int output_value ;
void setup() {
  // put your setup code here, to run once:
  pinMode(3,OUTPUT);
     Serial.begin(9600);
   Serial.println("Reading From the Sensor ...");

  lcd.begin(20, 4);
  delay(4000);
}

  // put your main code here, to run repeatedly:

  void loop() {
  lcd.clear();
  dht.begin();

  float humid = dht.readHumidity();
  float temp = dht.readTemperature();

  lcd.setCursor(0, 2);
  lcd.print("Temperature: ");
  lcd.print(temp);
  lcd.print("C");

  lcd.setCursor(0, 3);
  lcd.print("Humidity: ");
  lcd.print(humid);
  lcd.print("%");

 pinValue = analogRead(sensor_pin);
 output_value = map(pinValue,700, 300,0,100);

  Serial.print("Mositure : ");
  Serial.print(output_value);
  Serial.println("%");
   if(output_value> 0 && output_value <= 51){
    digitalWrite(3,LOW);
    lcd.setCursor(0,0);
    lcd.print("ON");
    lcd.setCursor(0,1);
    lcd.print("MOISTURE VAL: ");
    lcd.print(output_value);
    lcd.print("%");

    delay(1000);

     }else if(output_value > 51 && output_value <= 100){
      digitalWrite(3,HIGH);
      lcd.setCursor(0,0);
      lcd.print("OFF");
      lcd.setCursor(0,1);
      lcd.print("MOISTURE VAL: ");
      lcd.print(output_value);
      lcd.print("%");

      delay(1000);

     }
     delay(1000);
}

EDIT (1)

Here are some pics of the circuitry and the LCD message. If you find these pictures to not be helpful, I can sketch this circuit. Thank You.


texts: How to utilize SPI Serial bus on a ATSAMD21G18?

texts: Like the title suggests, I have a ATSAMD21G18 microcontroller that I want to interface with a LTC6803-4 chip, but I'm not sure how to set up the SPI bus on the microcontroller, and the datasheet proved too confusing for me to understand.


texts: How do I send a string to master using i2c

texts:
I want to write an Arduino program that simply recieves a string (via the I2C wire library) from a master Arduino, then waits for a request, and sends that string back.

Here is my code:

#include <Wire.h>

void setup()
{
  Wire.begin(4);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
}

String data = "";

void loop()
{

}

void receiveEvent(int howMany)
{
  data = "";
  while( Wire.available()){
    data += (char)Wire.read();
  }
}

void requestEvent()
{
    Wire.write(data);
}

I read in the API that the write() function accepts a string, but I keep getting a "No matching function for call" error.  I tried to simply replace

Wire.write(data);

with

Wire.write("test");

and that worked without error.  Why is this the case?


texts: Why did my pushbutton LED circuit work when my wiring was wrong?

texts:
I had a Coursera Arduino homewhere wherein you create a simple pushbutton-controlled LED circuit.

I used the example "button.ino" script that's builtin to the Arduino IDE, without modification. I'll reproduce it at the end of this question.

Here's what I did (wrong):

My circuit went from 5V Power to the top pin of a push button. The bottom of the pushbutton was (correctly) wired to Pin 2 on one side and a resistor was used to wire the other bottom pin to the anode of LED. The cathode of the LED was wired to ground.

The reason I think this is wrong is that I forgot that I was supposed to wire the LED to a pin corresponding to ledPin in the example script. The example script uses Pin 13, which has the builtin LED. I was using an external LED. Yet, the circuit worked perfectly.

Why did it work? Doesn't that mean the 5V power output was getting turned off (I'd guess you call that being set to LOW) when Pin 13 was set to LOW? Why would that be the case?

/*
  Button

 Turns on and off a light emitting diode(LED) connected to digital
 pin 13, when pressing a pushbutton attached to pin 2.

 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground

 * Note: on most Arduinos there is already an LED on the board
 attached to pin 13.

 created 2005
 by DojoDave <http://www.0j0.org>
 modified 30 Aug 2011
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Button
 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

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

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}


texts: Arduino Newbie: Solderless Breadboard Alternate

texts: I am completely new to arduino. I have created a circuit using solderless breadboard. But obviously the connections are lose or not as good as a soldered solution. So I was wondering since I am new to circuits too, what is the easiest


texts: Arduino MKRZero malfunctioned after trying to load a program

texts:
I have an Arduino MKRZero that I tried to load the following program into:

#include <FastLED.h>

#define NUM_LEDS 60
#define ledPin 4;

AudioFrequencyMeter meter;
CRGB leds[NUM_LEDS];

void setup() {
  Serial.begin(9600);
  meter.setBandwidth(70.00, 1500);
  meter.begin(A0, 45000);
  FastLED.addLeds<WS2812B, ledPin, RGB>(leds, NUM_LEDS);
}

void loop() {
  float frequency = meter.getFrequency();
  Serial.println(analogRead(A0));
}

After which, the Arduino IDE said:
"Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload."

And windows gave this message:

The board is dead for all I can tell. The light still comes on when I connect it to my computer and when press reset, windows makes the "you just plugged something in" sound, but it doesn't work. Can anyone tell me what happened?


texts:
so I'm working on communication between arduino and RPi via GPIO pin.
It's basically connecting them by using a cable jumper. So I have a 2 channel relay shield attached to my arduino, and I've been wondered how do I connect them to RPi. I need help for this problem, any advice would be appriciated. I'll post the GPIO pin below.
Thankyou


texts:
I am using Arduino Uno, and MPU6050(3 axis imu sensors), not gate,  and L298 dc motor drive.

My algorithm is very easy.
Receive an angle how the balancing robot is tilt.
Decision speed of motors by using the angle.
For example, when robot is tilt n degrees forth or back, robot will go forth or back with speed proportional n.

My code is similar to the following code.
Sorry, it is difficult to type on my phone. TT

Angle = getComplementaryAngle();

Speed = pidCompute(abs(Angle));
// Speed range: 0 to 255

if (Angle > 0.4) {

  DigitalWrite(dirA, HIGH);

  DigitalWrite(dirB, HIGH);

  analogWrite(enA, Speed);

  analogWrite(enB, Speed);

}

else if (Angle < -0.4) {

  DigitalWrite(dirA, LOW);

  DigitalWrite(dirB, LOW);

  analogWrite(enA, Speed);

  analogWrite(enB, Speed);

}

else {

  analogWrite(enA, 0);

  analogWrite(enB, 0);

}

I don't know why left motor's speed is different from right motor's one.
I checked the voltage of motor pin.
Both pins' voltage are same as 11V.
I think pwm is wrong.

When Arduino makes two pwm output, it causes some problems?