texts: LED and MOTOR "ON" when A BLE DEVICE APPROACH ESP32 MICROCONTROLLER DFR0575

texts:
I have this code that is working perfectly but I want my device to start vibrating too (right now only the led is working)

On a Wemos Battery Module I have simply connected the vibration motor on the same PIN of the LED and it works perfectly.

Now I want to do the same on an Beetle ESP32 Microcontroller DFR0575. I used the same code But I can't make the module vibrating (The led light is working perfectly)

this is the code:

 #include <BLEAdvertisedDevice.h>
   #include <BLEDevice.h>
   #include <BLEScan.h>

   const int PIN = 2;
   const int CUTOFF = -50;

   void setup() {
     pinMode(PIN, OUTPUT);
     BLEDevice::init("tkr");
   }

   void loop() {
     BLEScan *scan = BLEDevice::getScan();
     scan->setActiveScan(true);
     BLEScanResults results = scan->start(1);
     int best = CUTOFF;
     for (int i = 0; i < results.getCount(); i++) {
       BLEAdvertisedDevice device = results.getDevice(i);
       int rssi = device.getRSSI();
       if (rssi > best) {
         best = rssi;
       }
     }
     digitalWrite(PIN, best > CUTOFF ? HIGH : LOW);
   }


texts: Arduino code for thermistor respiratory monitor

texts:
I have designed a thermistor-based respiratory monitor which detects changes in temperature during respiration, but I am having problems with the coding part. Can someone help, my code given below is not working.

void setup() {
  Serial.begin(9600);
}
unsigned long timer;
void loop(void)
{
    delay (500)
  int sensorValue = analogRead(A0);
timer=millis ();
    if ( sensorValue<200) {
unsigned long currentTime = millis();
float period_respiration = currentTime-timer;
float breathrate= 60000/period_respiration;
Serial.println("Respirations per minute:");
Serial.println(breathrate);
  }
}

The sensor value is 600-800 during inspiration, and about 100 during expiration.


texts: Can I reduce UIPEthernet library size (perhaps by ditching TCP)?

texts:
I am using the excellent UIPEthernet library to get an Arduino Nano to drive an ENC28J60 Ethernet Shield for a UDP-based application. But I think the poor library has to do a lot of work to make up for the limitations of the ENC28J60, and that makes the library large compared to the W5x00 family devices.

My sketch is starting to run out of the 32K (actually 30720 bytes) program space; I'm at 26K and I've still got functionality to add. Right now, the application is using DHCP to get the IP address, it picks up UDP discovery broadcasts from a controller PC on the LAN and then asynchronously chats to it (and only it) with UDP msgs. My uip-conf.h, condensed, looks like:

#define UIP_CONF_MAX_CONNECTIONS   0
#define UIP_CONF_MAX_LISTENPORTS   0
#define UIP_CONF_BUFFER_SIZE      98
#define UIP_CONF_TCP_MSS          64
#define UIP_CONF_RECEIVE_WINDOW  256
#define UIP_CONF_LOGGING           0
#define UIP_CONF_UDP               1
#define UIP_CONF_UDP_CONNS         2
#define UIP_CONF_UDP_CHECKSUMS     1
#define UIP_CONF_BROADCAST         1
#define UIP_CONF_STATISTICS        0

So I'm looking at ways to shave some KBs. There is much made of the fact that you can disable the library's UDP subsystem to save ~5KB (which is sort of how much I'm looking for, maybe less, though more is always nice!). And I was rather hoping I could disable TCP, but I can't see an easy way.

Are there any configurations or tricks I can play with UIPEthernet to save code space, given I'm not using TCP?

(I do have other options: switch to a W5x00 board, get a CPU with bigger memory, etc - but I want to explore this option before I revise the hardware spec).


texts: How to write IF/Else using a threshold range of values

texts:
basically I am trying to write an IF/ELSE statement that triggers a light when a pressure sensor is between two values.

In other words, I want the light to respond ONLY if the analog read is between 400 and 600, as opposed to, say, only being above 400.

Here is the code, any suggestions?

int sensor=0;
int threshold=200;

void setup (){
  pinMode(2, OUTPUT);
  digitalWrite(2, LOW);
  Serial.begin(9600);
}

void loop() {
  sensor=analogRead(0);
  Serial.println(sensor);
  if (sensor > threshold) {
    digitalWrite(2, HIGH);
  }
  else {
    digitalWrite(2, LOW);
  }
}


texts: Change the sequence of LEDs with button press

texts:
I am new to arduino.
I have created a circuit , here is the image:

I want something that as I press the button the sequence of LEDs will change and as I press the button again , the sequence will change again.

I programmed code as following but it don't works correctly:

int led1 = 11;
int led2 = 10;

int output = 2;
int input = 4;
int mode = 0;

void setup() {
  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
  pinMode(output,OUTPUT);
  pinMode(input,INPUT_PULLUP);
  digitalWrite(output,LOW);

}

void loop() {
  while(mode == 0 && digitalRead(input) == 1){
    digitalWrite(led1,HIGH);
    digitalWrite(led2,HIGH);
    delay(100);
    digitalWrite(led1,LOW);
    delay(100);
    digitalWrite(led1,HIGH);
    delay(100);
    digitalWrite(led2,LOW);
    delay(100);
    digitalWrite(led2,HIGH);
  }
  if(digitalRead(output) == 0){
    mode++;
    if(mode >= 2){mode = 0;}
  }
  while(mode == 1 && digitalRead(input) == 1){
    analogWrite(led1,255);
    delay(400);
    analogWrite(led1,150);
    delay(400);
    analogWrite(led2,255);
    delay(400);
    analogWrite(led2,150);
  }

}

According to the above code , two leds led1 and led2 are connected with arduino. When the button is off the both LEDs turns on then led1 turns off then turn on again , next time led2 turns off and turns on again.As the button will be pressed , brightness of led1 will be less than the brightness of led2 and then
will again be equal to the brightness of led2, then brightness of led2 will be less than the brightness of led1 and then will be equal to the brightness of led1. But as I press the button , nothing happens but the led1 and led2 keeps turning on and off . However sometimes when I press the button then it works.

What is the problem with my code and how to solve it?


texts: Cannot set MOSI pin low even after ending SPI

texts:
I'm building a battery operated device and must shutoff MOSI pin during sleep because it leaks current through the SD card if I don't (about 400 µA).

Problem is, it won't stay off.  I've looked at SPI documentation and as far as I know I just need to call spi.end() then set pinmode to output and finally digitalWrite LOW.  I observe with an oscilloscope that it does go low upon my asking it to but only for about 1 µs (actually it goes low twice within a 5 µs time period).

I've also tried manually setting the pin low using the PORT registers and the behavior is the same... see relevant code:

spi.end();

//pinMode(pin_MOSI, OUTPUT);
//digitalWrite(pin_MOSI, LOW);

//Both above (commented out) and below result in the same behavior -- pin does not stay LOW

DDRB |= B00100000;            //set pin 5 as output
PORTB &= B11011111;           //set output low for pin 5

delay(5000);

...As you can see there is a delay to ensure that it isn't being set high by some other code.

Is there some sort of SPI interrupt that automatically sets the pin high again?

Hardware details:

MCU: ATMEGA1284P;
Programmer: Atmel-ICE

UPDATE (13-Mar-2019):

I didn't realize that SPI is implemented by Atmel in hardware directly (see datasheet page 105):

  MOSI/PCINT13 – Port B, Bit 5
  – MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI0 is enabled
  as a slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI
  is enabled as a master, the data direction of this pin is controlled by DDB5. When the pin is
  forced to be an input, the pull-up can still be controlled by the PORTB5 bit.

I am currently chasing down this latest information and will hopefully come to a resolution soon.  I will post any progress.


texts:
I am using DHT22 temperature/humidity sensor and I noticed that there exist so many libraries. I wonder which one is the most accurate?

It is giving me readings that does not seem to be logic. High temperature and very low RH%. Is it because of the library or because I am not connecting 10k or 4.7k resistor?

Thank you so much in advance.

Regards,
Badr Eddine


texts: I am a newbie and I would like to build my own minimalistic ATmega32U4 based arduino compatible board. Can anyone please tell me which parts resistors/capacitors (and maybe one status led) I need to connect it over usb to my computer? Thanks in advance.


texts: Calibrating Adafruit TCS34725 for RGB colors

texts:
I am new to Arduino. I am currently working on a project which requires color detection using the TCS34725 Adafruit sensor module.
For the project, I need to calibrate the sensor with RGB colors. Color patches of RGB will be exposed to the sensor. After exposing each color patch, a push button will be pressed and then the calibration for that color should start.

Calibrate for Red

Calibrate for Green

Calibrate for Blue

After calibration, the sensor needs to detect the colors of objects.
I have no idea what is meant by calibrating the sensor for RGB values. Can someone please be kind enough to explain it to me.
Thank you in advance.


texts: Will 5V 2A current input to the power port kill my Arduino?

texts: I want to power my Arduino with a mobile charger, the out put is 5V 2A, will it kill my Arduino? And what's the max input current as power source?


texts:
Is it possible to query the pin-out and each pin's attributes at run-time with Arduino?

If not, can it be done at compile-time?

Finally, if not, how can I incorporate this kind of information into my project to avoid completely rewriting my program for each possible Arduino model?

I am looking for something like this:

PinProperties props= getPinProperties(pinNumber);

props.supportsDigitalInput();
props.supportsDigitalOutput();
props.supportsAnalogInput();
props.supportsAnalogOutput();
props.supportsPWM();
props.analogInputBits();
props.analogOutputBits();
props.pullupResistance();
props.pulldownResistance();

etc.

NOTE: This question is similar and I might use the board model to look up a pre-stored pin-out.


texts:
Ok so forgive me for being an amateur but I'm having a situation that's driving me nuts.

I have a sensor that I have to cycle between +5VDC and +1.4VDC every 60 seconds. I'm using an ATTiny85 with the 8Mhz internal clock fuse set.

What I was hoping was to use a 2N7000 N-Channel MOSFET to control the cycling of the voltage. So my thought is to have +5VDC on the Drain and a PWM signal on the Gate with the + side of the sensor connected to the Source. I am thinking that using PWM and adjusting the duty cycle on the Gate will allow me to adjust the voltage that is seen at the Source but what I'm seeing is a variation of +1.4VDC @28% duty cycle and +3.6VDC at 100% duty cycle.

I can't figure out why +3.6VDC is the best I can do. The PWM is coming from PB1 on the ATTiny85 and the +5VDC is coming from the main voltage source that also feeds the ATTiny85. The current draw of the sensor is 140mA max.

Ok so I haven't had any luck using a BJT or a single component to perform this voltage change so I started on a different approach using two 1N7000, with one being in an inverter configuration.  My though is the pin from the MCU will go high, which will turn on both FET's, with one supplying 5V and the other sinking to ground.  When the MCU pin goes low, both FET's turn off, which stops the 5V flow and the sink to ground, which then will allow the path through a voltage divider into my sensor at 1.4V.  The issue I am having is the second FET is smoking, and by that I mean the sucker heats up like crazy and one even let the smoke out!  I cannot for the life of me figure out WTF I am missing in this configuration.  Here is the new schematic and Q1 is the FET that is smokin.


texts: What's wrong with infinite loops inside loop()?

texts:
I wanted to run the following code as something similar to Tone or pwm. However for some reason that I am unable to seek it doesn't work.

#define WAIT 3200UL

void setup() {
  DDRB |= B00000001;  // set pin8 as output
}

void loop() {
  unsigned long t;
  while (1) {

    PORTB &= B11111110; // clear pin 8
    t = WAIT;
    for (t = 0 ; t < WAIT; t++);

    PORTB |= B00000001; // set pin 8
    t = WAIT;
    for (t = 0; t < WAIT; t++);

    //            PORTB &= B11111110;
    //            delayMicroseconds(WAIT);
    //            PORTB |= B00000001;
    //            delayMicroseconds(WAIT);

  }
}

the code is pretty simple, just toggling a pin. If I use the commented section, it works fine but as is, it doesn't work.

I removed the "while(1)" statement since it was unnecessary for now, it started to work improperly, (changing the WAIT didn't have any effect and I'm not sure I'm getting a full swing).

Pin 8 is connected to an LED + R to ground and a piezzo in parallel to them. the LED seems to be steady on yet the buzzer makes a low noise. I measured a   voltage of 3.8v DC and arround 9v AC on the pin, other pins I ran the code for were similar.

As another attempt I put a Serial.print in the beginning of the while(1) but it printed out only once.

Also looked at the assembly code generated for a clue to find out what does delayMicroseconds() do but couldn't figure out what's wrong.

Appreciate your help.


texts: Last element of a struct disappearing on write/read

texts:
I'm building a weather station with two UNOs, using NRF24l01+ radios. Communications are fine. I'm sending a struct from one to the other. The struct has three elements:

    struct weather {
      float tempData;
      float humData;
      float pressData;
    };
    weather wData = {0, 0, 0};

I then populate the struct with values from my DHT22 Temperature Sensor and my BMP085 pressure sensor.

    float c = dht.readTemperature();
    wData.tempData = (c * 9/5) + 32;
    wData.humData = dht.readHumidity();

    sensors_event_t event;
    bmp.getEvent(&event);
    wData.pressData = (0.0295 * event.pressure);

Now I send it via the NRF24L01+.

    radio.write(&wData, sizeof(wData);

On the receiving Uno I have this.

    struct weather {
      float tempData;
      float humData;
      float pressData;
    };

    weather wData = {0, 0, 0};

    radio.read( &wData, sizeof(wData) );
    Serial.println(wData.tempData);
    Serial.println(wData.humData);
    Serial.println(wData.pressData);

I get results similar to this:

    Temp = 75.43
    Hum = 35.76
    Press = 0.00

The first two are correct. The final one is not. I can change the order and the first two will always be correct, but the last element is always 0.00. For example:

   Hum = 35.76
   Press = 30.14
   Temp = 0.00

I know I'm missing something here with my code but I can't find it. Anyone have some suggestions?


texts: How to catch the Enter key received by Bluetooth?

texts:
I got some code to receive characters from Bluetooth and code and print it back to the LCD display.

However, want to detect the Enter character to be the input signal, in other words, not to print nothing to the display until Enter is pressed.

An strange character is shown at display for Enter but I can't catch it.

This is my code:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x20,16,2);

void setup()
{
  lcd.init();
  lcd.backlight();
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  Serial1.begin(9600);

}

void loop()
{

  while (Serial1.available())
  {
    char dato= Serial1.read(); //Comprobamos el dato

     lcd.print(dato);

    switch(dato) {
    case '#':
      Serial.println("GATO...");
    break;
    case 'e':  digitalWrite(13,LOW);

    Serial1.println("Led apagado");
    break;
      case 'r':
      digitalWrite(13,HIGH); delay(200);
      digitalWrite(13,LOW); delay(200);

      Serial1.println("Led intermitente");
      break;
  } //fin switch

}//serial disponible

}//fin programa


texts: Using HC-08 bluetooth module with arduino

texts:
I have an arduino mega 2560 and a recently purchased HC-08 module and the connection is as the following:
Arduino | HC-08
VCC - VCC
GND - GND
14TX3 - TXD
15TX3 - RXD
When I power up the arduino it shows that flashing light and I am able to see it on my android phone but would only reject the connection every time I tried to pair. Also I am not able to send or receive any data from it at all, here is my code:
#include <SoftwareSerial.h>

SoftwareSerial hc08(15,14) // RX pin, TX pin;

void setup(){
  //Initialize Serial Monitor
  Serial.begin(9600);
  Serial.println("ENTER AT Commands:");
  //Initialize Bluetooth Serial Port
  hc08.begin(9600);
}

void loop(){
  //Write data from HC08 to Serial Monitor
  if (hc08.available()){
    Serial.println("Reading from bluetooth");
    Serial.write(hc08.read());
  }

  //Write from Serial Monitor to HC08
  if (Serial.available()){
    Serial.println("Writing to bluetooth");
    hc08.write(Serial.read());
  }
}

I'd really appreciate help on how to get it working.


texts:
I wrote a simple code on lillypad with fdti module as below:

void setup(){
Serial.begin(57600);
}
void loop(){
 Serial.println("ddd");
 delay(500);
}

but it gives wrong characters at serial port window of arduino ide at 57600 baudrate. But I changed baudrate to 115200 at same window it gives right string as "ddd". Other baudrates do the same thing. What is the solution or where is the problem. I couldnt understand why baudrate shift occurs


texts: What is the memory expense of creating a String from a char array?

texts:
I'm writing a little API for processing email messages in Arduinos. Obviously, I need to keep memory use down, but I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.

My logic uses char arrays (so that memory is statically allocated). If my end user converts a char array to a String (so that they can easily see if an email subject startsWith() a particular word) will this result in doubling the character memory used? .. or will the String class simply include a pointer to the original char array (and just add some cruft)?

What would be the best-practice in this kind of situation?


texts: How can I attach I2C sensors on the small board of Intel Edison?

texts: Sensors like Skin conductance, Body temperature and Heart Rate. Please imagine to talk to a child and keep the answer very simple so I can understand you and you don't lose time to write explanations for your answer.


texts: 16 channel Relay module led is ON when pin is LOW and  OFF when pin is HIGH, how to reverse that?  Could you please help me


texts:
i've got a huge (about 6 x 23 cm) graphics LCD. I used my multimeter and the datasheet the LCD driver chips (6 x KS0104 and 2 x KS0103) to get the pinout. It has the following pins: GND, M, FCS (not 100% shure), CL1, CL2, D0-3, VDD and a ground for the metal part.

My problem is that i dont know how i can drive a 4bit GLCD with an Arduino because i didnt found a library which can do this (e.g. OpenGLCD supports only the KS0104 which is an 8 bit controller)


texts: Why would a serial device not be sending the correct start code?

texts:
I am unable to get any reading from a PMS5003 connected to an ESP32.
In trying to debug this problem, I have a very minimal setup. Only the PMS5003 is connected to the ESP32, and using the following the code.
#include <Arduino.h>
#define PMS_DEBUG
#include <PMSerial.h>

SerialPM pms(PMSx003,Serial2)

void setup() {
  Serial.begin(9600);
  Serial2.begin(9600);
  pms.init();
}

void loop() {
  pms.read();
  Serial.println(pms.pm25);
  Serial.println(pms.status);
}

pms25 always returns 0. When the PMS5003 is properly connected to the ESP32, status always returns "Wrong message start".
Why would the device be sending the wrong start code, and what steps can I take to debug this?
I have tried connecting to different serial pins, including following the ESP32 software serial example provided by the PMSerial library. In all cases, it simply looks as though the PMS5003 sensor is mot transmitting anything - indeed no fans are switching on and there is no sign of life at all from the device. However, I am very much a beginner, and don't know enough to tell whether this is a problem with the device, the library or something I have done.
Very grateful for suggestions how to debug this.
Edit
example serial data
0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x6D, 0x0, 0xE0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x97, 0x0, 0x0, 0x0, 0xF8,

0x0, 0x0, 0x0, 0x0, 0xA, 0x0, 0x0, 0x1, 0x0, 0xB0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0xBB, 0x1, 0x0, 0x5F, 0x0,


texts:
I've been trying to work with Waveshare SIM 808 shield on arduino, quite similar to this one:
https://www.waveshare.com/wiki/GSM/GPRS/GPS_Shield_(B)#How_to_use_with_Arduino_UNO_R3

I tried using multiple examples, such as this:

#include <DFRobot_sim808.h>

#include <SoftwareSerial.h>

DFRobot_SIM808 sim808(&Serial);

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

  //******** Initialize sim808 module *************
  while(!sim808.init()) {
      delay(1000);
      Serial.print("Sim808 init error\r\n");
  }

  //************* Turn on the GPS power************
  if( sim808.attachGPS())
      Serial.println("Open the GPS power success");
  else
  Serial.println("Open the GPS power failure");

}

void loop() {
    //************** Get GPS data *******************
    if (sim808.getGPS()) {
    Serial.print(sim808.GPSdata.year);
Serial.print("/");
Serial.print(sim808.GPSdata.month);
Serial.print("/");
Serial.print(sim808.GPSdata.day);
Serial.print(" ");
Serial.print(sim808.GPSdata.hour);
Serial.print(":");
Serial.print(sim808.GPSdata.minute);
Serial.print(":");
Serial.print(sim808.GPSdata.second);
Serial.print(":");
Serial.println(sim808.GPSdata.centisecond);

Serial.print("latitude :");
Serial.println(sim808.GPSdata.lat,6);

sim808.latitudeConverToDMS();
Serial.print("latitude :");
Serial.print(sim808.latDMS.degrees);
Serial.print("\^");
Serial.print(sim808.latDMS.minutes);
Serial.print("\'");
Serial.print(sim808.latDMS.seconeds,6);
Serial.println("\"");
Serial.print("longitude :");
Serial.println(sim808.GPSdata.lon,6);
sim808.LongitudeConverToDMS();
Serial.print("longitude :");
Serial.print(sim808.longDMS.degrees);
Serial.print("\^");
Serial.print(sim808.longDMS.minutes);
Serial.print("\'");
Serial.print(sim808.longDMS.seconeds,6);
Serial.println("\"");

Serial.print("speed_kph :");
Serial.println(sim808.GPSdata.speed_kph);
Serial.print("heading :");
Serial.println(sim808.GPSdata.heading);

//************* Turn off the GPS power ************
sim808.detachGPS();
  }

}

or this

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX
String comdata = "";
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

 while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  delay(200);
}

void loop() // run over and over
{
  delay(2000);
   mySerial.println("AT");
   delay(200);
   //Send message
   mySerial.println("AT+CGNSPWR=1");
   delay(200);
   //reset GPS in autonomy mode
   mySerial.println("AT+CGNSTST=1");
   delay(200);
   mySerial.listen();
   while(1)
  {
    while(mySerial.available()>0)
        Serial.write(mySerial.read());
    while(Serial.available())
    mySerial.write(Serial.read());
  }
}

In first case, I obviously don't declare RX, TX pins and use the Arduino's general purpose RX, TX pins (0, 1).

In second case I used wires to connect Arduino pins 2 and 3, to shield's D0 and D1 pins.

In both cases, neither RX or TX leds on shield's module light up, which means that it doesn't receive the sent data.

I made sure to set UART/ARDUINO switch on ARDUINO position and I did reset the module several times.

I am using Arduino Uno. What goes wrong here?


texts: What would be the best way of dynamically 'change' instances regarding dynamic memory?

texts:
Since I'm very used to object oriented programming, I would like to use this into my design.
My application will have 4 led strips and each led strip will have a 'pattern' running on it. For this I like to create a base class and for each pattern a derived class. So this means I have 4 instances to a pattern. However, the pattern can change dynamically (based on music MIDI input). Each pattern has between 10-16 parameters.
I know dynamic memory allocation is mostly not a good idea in an Arduino. I'm using a Mega which has 8 KB. I found several 'solutions' but neither one I'm sure about. The first is not the solution but the way I should do it when I have 'plenty' of SRAM available (and simplified):
class Pattern
{
   public:
      virtual void Process();
}

class PatternA: Pattern
{
   public:
      void Process();

      // In example I only use 2 out of 10-16 parameters
      uint8_t SetColor(uint8_t colorIndex);
      uint8_t SetSpeed(uint8_t speed);

   private:
      uint8_t _colorIndex;
      uint8_t _speed;
}

// In this example I only use 2 out of 24 patterns
class PatternB: Pattern
(like PatternA but with its own implementation)

class LedStrip
{
   public:
       void SetPattern(Pattern* pattern);

   private:
       Pattern* _pattern;
}

Other derived classes may have other (named) parameters.
When changing instances, I would get something like this:
LedStrip::SetPattern(Pattern* pattern)
{
    delete _pattern;
    _pattern = pattern;
}

pattern* pattern = new PatternA(...);
ledStrip1.SetPattern(pattern);

However, since the new pattern may use more memory then the deleted pattern, there will be a memory gap. So this is not suitable for the Arduino to be used I assume.
Solutions:
1. Create all possible patterns beforehand.
Assume I would implement 24 patterns, and create any possible combination, I would have 4 (led strips) * 24 (patterns) * 13.5 (average number of parameters) = 1,296 bytes. This seems a bit much as only 4 are 'active'.
class LedStrip
{
   public:
      enum EPattern {A, B}

      void SetPattern(EPattern pattern);

   private:
      PatternA* _patternA;
      PatternB* _patternB;

      Pattern* _pattern;
}

To change pattern:
void LedStrip::SetPattern(EPatternpattern)
{
case EPatternA: _pattern = _patternA; break;
case EPatternB: _pattern = _patternB; break;
}

ledStrip1.SetPattern(EPattern::A);

Of course I could also pass a pattern where the patterns are created globally but this is does not matter for this example. The idea is to create 4 (led strips) * 24 (patterns) instances beforehand and never use delete. This means out of the 4 * 24 patterns, only 4 are used, 1 per led strip.
Of course this causes a lot of unused memory.
2. New/Delete
I create the 4 correct derived instances and when one pattern (instance) change, I delete the instance and create the new. When I put no (instance) variables in the derived class, this could work, but I have some specific questions regarding this solution:
I make sure all the max. parameters are in the base class and I 'cast' 4 instances of the base class to a derived class. This seems a bit of 'tricky' solution.
class Pattern
{
   public:
      SetParameter(uint8_t parameter, uint8_t parameterValue);
      uint8_t parameter GetParameter(uint8_t parameter);

   private:
      uint8_t _parameters[16];
}

class PatternA: Pattern
... (does not have any variables)

To change pattern:
delete ledStrip1.pattern;
ledStrip1.pattern = new PatternA();

Question: can I assume the deleted memory of the old pattern will be replaced by the new pattern as the memory usage is equal?
The downside of this way is that each pattern will have the worst-case amount of parameters in each instance, but this is not a problem (I only have 4 led strips).


texts: why does it use A0 to define analog pin 0 in some case and why use 0 directly?

texts:
https://www.arduino.cc/en/Tutorial/AnalogInput

https://www.arduino.cc/en/Tutorial/Knob

For first line of both examples(not in comments), it define the same pin, analog pin 0, but they use different values. why and can use A1, A2, etc. to define other analog pins?


texts: Will we be able to burn arduino zero pro's bootloader?

texts: As arduino.org states, the bootloader is pre-burnt by Atmel at the factory. I'd like to know if it will be possible for us to buy "raw" ICs and burn them at home for our own boards, as we do with the Atmega328 for example.


texts:
I'm new to Arduino and haven't done any education in electrical engineering before, so this might be a very dumb question.

I'm busy with a project to control two servo motors with Arduino. Now yesterday I connected the wires incorrectly to the breadboard, so the wires started smoldering. I didn't connect the resistor correctly, so I guess that might have been the problem.

Now I replaced the wiring, but it's not working and I don't know if the software might be the problem or the breadboard need to be replaced as well. I cannot see anything wrong with the breadboard, but it was warm so I don't know if it might be burned from the inside? The wiring of the servomotors seems to be okay, so I guess that I don't need to replace those I hope.

Any tips about how to check everything is still working?

Or might it be a good idea to buy an LED and add it to the breadboard to ensure it's okay?

EDIT:
I guess I found some code to check that the servomotors are still okay. Just add them directly to the Arduino and run some code: Sweep

One other question: one of the servomotors doesn't have a black, red and yellow cable but a red, brown and orange. How can I know which ones the same as yellow, red and black?


texts: Arduino Mega external interrupts fire randomly

texts:
I'm trying to solve a nagging issue with external interrupts - this is for a slot car track lap count controller. It uses the Mega's 6 external interrupt lines connected to photo diodes. The HW itself works fine - yes, trust me, it's fantastic.

I have observed the following. The code in the loop() is surrounded with:

detachAllInterrupts();
delay(10);
...
... process any interrupts and/or button presses
...
delay(10);
attachAllInterrupts();

If I omit or reduce the delay amount the random firing gets worse.

The ISR is lean and mean:

void lapDetected1() {
  lane1.lapDetected();
}

calling the method of class Lane:

    void lapDetected() { // called by ISR, short and sweet
      now = millis();
      if ((now - finish) < laneProtectionTime) {
        return;
      }
      start = finish;
      finish = now;
      count++;
      reported = false;
    }

all the variables used are declared volatile.

I don't like to use delay and I'm seeking advice on how to correctly implement ISRs and their handling.

here's the link to the entire code on GitHub: https://github.com/gabe2001/PCLapCounterWithArduino/

Thanks for any advice I can get here!
-gabe


texts: Digital pin output voltage, not triggering 71mA relay coil

texts:
I have a relay (VRS4H-S-DC5V-C), for which the triggering voltage required is 5V Min.  If I directly use the 5V voltage of Arduino  I'm able to trigger it, but if I use any digital pin in OUTPUT mode in digitalWrite I'm not able to trigger the relay.

Earlier I thought that it must be that because it's a small board its digital pins would be giving HIGH state as 3.3.V, but the fact is when I checked both the voltage of 5V (which is obviously shown 5V on multi meter) and that digital pin one, both show 5V. So the question is why the hell is digital pin not able to trigger the relay, since trigger the relay by 5V is of no use for me since I can't control it, i.e., when it should trigger and when not?


texts: Modifying smart watch or activity armband with further sensors

texts:
I want something like an activity armband where I would like to add an bend sensor or EMG sensor for simple hand gesture recognition tasks. I could probably build it from scratch with arduino-like parts, but it will be much more bulky then the ones on the market and I would rather not reinvent those things that already do what I want. This is the type of device I am thinking about.

Is there an feasible task to try to modify an existing activity armband or smart watch by adding one of these sensors? If so, do you have any suggestions of what should be considered? Should I try something completely different? I am open to ideas.
I have a background in Physics and Computer Science with an basic understanding of electronic devices but I am eager to learn.


texts: Arduino-compatible wireless technology which can be suitable for transmitting data

texts:
Introduction

I've been meaning to build a vehicle using arduino components and LEGO. I have a mechanical clamp built with arduino which will be locked on top of a custom LEGO build (It should be made out of LEGO blocks and arduino sensors). In my mind, it resembles a crawler.

Question

I've been looking for a way of controlling it remotely.
I only have experience with IR controllers but I'm not sure if this technology would fit for my project.

What I'm looking for is a technology wich could transmit data to an Arduino board (thus, an emitter and a receiver component) which, in my case, could comfortably handle a veichle.

Plus, it should have a range of action of at least 5 meters (15 ft).

If such technology exists, do you know any controller which could do the job for me?


texts:
HC-05 Bluetooth RX requires 3.3 v (TX has a regulator built in)
I understand my uno and nano are 5v
Ive connected a 3.3v Zennor in series with a led and resistor and with multimeter established the black stripe goes ground to achieve 3v
But which is considered ground between hc-05 RX or the arduino TX that it connects to..
Is this an acceptable way to drop the voltage?
If not I've ordered some small voltage regulators.
But I still have the same question, which way round.
The regulator has connections v1...gnd...vo
Thanks Paul
(Edit to this post)
Ive read a bit more and if correct I now think the Hc-05 rx connects direct with the arduino tx and the Zennor connect anode to the link and stripe side to ground...
Still unsure..


texts:
I have a Geeetech Iduino Yun Shield. I accidentally flashed the wrong firmware image (not the sysupgrade) to the board. I then tried using the Yun UBoot Reflash method. However, when I open the console monitor from the IDE and restart/reboot the board, I do not get the UBoot prompt. I have attempted to run it at least ten times without receiving any console/serial output.

EDIT: The shield is running on a Leonardo base board.

Is there anything I can do to load the correct firmware onto the board and get it operational or is the board truly bricked? If so, is it possible to obtain a new Atheros AR9331 board to replace the existing one or should I buy a new Yun?

Update: I have tried to get the shield to do an FTP boot, as detailed here by Majenko. I get to the stage where I get the dr_boot> prompt. However, when I type in tftpboot 0x81000000 dragino2-yun-common-v2.0.6-kernel.bin, I get no feedback; it just sits there indefinitely (unless I interupt the process). I can't figure out what I'm doing wrong.


texts:
I have to arduino's which are communicate using rx/tx. Arduino1 (A1) send data over serial to Arduino2 (A2). My questions are:

1 - If A1 do Serial.print each 50ms and A2 reading serial each 100ms which value will get A2? For example A1 send "1" and after 50ms send "2". Considering A2 will read serial after 100+ ms it will get "2" ?

2 - If A1 send data each 100+ms and A2 read at 50ms which value will get A2 between? For example A1 send "1" and A2 read "1" when read at 50ms but when it read again after 50ms (during that time A1 didn t sent anything ) will read again "1" ?

Thank you


texts: sending numbers from server to client (arduino mkr1010)

texts:
I want to send basic information from a server to a client. 4 numbers representing a random sequence
for example 0100. I have put this in byte array and use the "server.write" to send it to the client. At the client side I always get 4 times "255" when i print it on the monitor (when i print in on serial monitor on the server side it shows the right sequence numbers).

This is (only relevant part of ) my code on the server:

int sequence;
byte myseq[4]={0,0,0,0};
int i;
byte a;

void loop() {
  // wait for a new client:
  WiFiClient client = server.available();

  sequence=random(0,3);

for (i = 0; i < 4; i = i + 1) {
  if (i == sequence){
  a=1;
  }
  else{
  a=0;
  }
   myseq[i] = a;
     }

  // when the client sends the first byte, say hello:
  if (client) {
    if (!alreadyConnected) {
      // clead out the input buffer:
      client.flush();
      Serial.println("We have a new client");
      client.println("Hello, client!");
      alreadyConnected = true;
    }

    if (client.available() > 0) {
      // read the bytes incoming from the client:
      char request = client.read();
      Serial.print(request);
      for (i = 0; i < 4; i = i + 1) {
      Serial.print(myseq[i]);
      server.write(myseq[i]);

      }

    }
  }
}

the code on the client side

byte response[4]={0,0,0,0};

void loop() {

if (client.connect(ServerIP, 23)) {
  client.print("741G");
  //String response = client.readStringUntil('\n');
  for (i = 0; i < 4; i = i + 1) {
  response[i] = client.read();
  Serial.println(response[i]);

  }

  //client.stop();
}

Can somebody help me in explaining what i'm doing wrong ? what happens with the numbers once they get sent ? Apparently they arrive in a different format ?

thanks in advance !

ps : i see now that my sequence numbers are always 4 booleans (half a byte) maybe there is an easier way?


texts:
I have a sketch that prints out a value from 0 to 100.  I want it to take up the whole screen.
I can't figure out how to make the font bigger I think that the part of the code defines the size of the font is :
    oled.setFont(System5x7)

But if I alter the value 5x7 it just spits out errors messages.
This is all the code:
#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"
SSD1306AsciiAvrI2c oled;
#define I2C_ADDRESS 0x3C

int TankValue0;
int TankValue1;

void setup() {
  Serial.begin(9600);
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
  oled.setFont(System5x7);
  oled.clear();
}

void loop() {
  int sensorTankValue0 = analogRead(A0);
  int sensorTankValue1 = analogRead(A1);
  TankValue0 = map(sensorTankValue0, 300, 785, 100, 0);
  TankValue1 = map(sensorTankValue1, 300, 785, 000, 0);
  if (TankValue0 < 0) {
    TankValue0 = 0;
  }
  if (TankValue1 < 0) {
    TankValue1 = 0;
  }
  if (TankValue0 > 100) {
    TankValue0 = 100;
  }
  if (TankValue1 > 100) {
    TankValue1 = 100;
  }
  oled.print(TankValue0);
  oled.print(" L");
  oled.println(" ");
  //oled.print("T1=");
 // oled.print(TankValue1);
 // oled.println(" ");
  oled.setCursor(0, 0);
  delay(1000);
}


texts: How can I get my Attiny85 interupt to trigger

texts:
I have an ATTiny85 set up to detect a magnet passing over a hall sensor. Every 2 detection's I want it to light up an LED.

I decided to do the code using the arduino IDE and the code is as follows:

const int hallPin = 2;     // the number of the hall effect pin
const int ledPin =  1;      // the number of the LED pin

// variables will change:
volatile int hallState = 0;         // variable for storing the hall counter

void setup() {

  pinMode(ledPin, OUTPUT);
  pinMode(hallPin, INPUT);
  digitalWrite(hallPin, HIGH);

  // Attach an interrupt to the ISR vector
  attachInterrupt(0, pin_ISR, FALLING);
}

void loop()
{
  if(hallState>1)
  {
      digitalWrite(ledPin,HIGH);
      delay(2000);
      digitalWrite(ledPin,LOW);
      delay(2000);
      hallState=0;
  }
}

void pin_ISR()
{
    hallState++;
}

I've dry run this a bunch of times and cant see anything wrong with it. I use the digitalWrite on the hall pin to enable the internal pullup. But the circuit just doesnt work.

Here is the circuit:

I connected a multi meter to the hall effect sensor on its own just to check if it was working. I added an external pull up using a 10k resistor and it worked as expected 5v when no magnet present and almost 0 volts when a magnet is brought in range.

So my guess is my interrupt routine isnt working in my code, what could I be doing wrong? I've read in the documentation that pin 0 is the correct interrupt pin on the attiny85

Edit: Adding Schematic


texts: How to know if my Bluetooth HC-05 is connected through serial monitor

texts: I want to connect a Bluetooth module to arduino and check if my module is connected or not.. Through serial monitor. Is there and particular code to connect with that?


texts: Output works on UNO Pin 13, but not on 2?

texts:
I am experimenting with IR receive and transmit (basically I want my IOT to be able to turn on the TV, satellite receiver, and set the channel - yes, I am really that lazy).

I can receive and record the remote codes, and I can transmit the codes to an IR LED.

Now for the puzzle. I originally had my IR LED on Pin 13, but to clean things up I moved the output to pin 2 and changed the pin assignment in the sketch. Now it doesn't work. My phone camera shows that the IR LED is pulsing as before, but the appliance code is not working. Moving back to pin 13 and it works again.

So, what could be different between pins 13 or 2? I know that Pin 13 has the built-in LED but since I am setting it to output that shouldn't make a difference.

I am bit-banging to create the 38kHz pulses to the IR LED, so I am wondering if there is a latency difference from pins 2 and 13?

The sketch, since I know someone will ask for it:

int IRledPin =  13;
int buttonPin = 4;

void setup()   {
  pinMode(IRledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(buttonPin, HIGH); // pullup
  Serial.begin(115200);
}

void loop()
{
  if (! digitalRead(buttonPin)) {
    // button down
    Serial.println("Sending IR signal");
    SendCode();
  }
}

// This procedure sends a 38KHz pulse to the IRledPin
// for a # of microseconds.
void pulseIR(long microsecs) {
  // we'll count down from the number of microseconds we are told to wait

  cli();  // this turns off any background interrupts
  while (microsecs > 0) {
    // 38 kHz is about 13 microseconds high and 13 microseconds low
    digitalWrite(IRledPin, HIGH);  // this takes about 3 microseconds
    delayMicroseconds(10);         // hang out for 10 microseconds
    digitalWrite(IRledPin, LOW);   // this also takes about 3 microseconds
    delayMicroseconds(10);         // hang out for 10 microseconds
    // so 26 microseconds altogether

    microsecs -= 26;
  }
  sei();  // this turns interrupts back on
}

void SendCode() {
  // This is the code for my FIOS FF
Serial.println("FIOS- FFwd");
  pulseIR(9220);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(22320);
  pulseIR(9200);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2260);
  pulseIR(520);

}


texts: invalid conversion from 'uint16_t* error when creating an array of uint16_t items


texts: ESP8266 not sending temperature data to text message

texts:
i am trying to use a ESP8266 module to send temperature data using twilio and send it to my phone via text message. However it does not send the sensor data but the text i placed. Is it possible if i can get it to send sensor data instead? If so how can i do this?

strcat(data,"From=");
    strcat(data,PHONE_FROM);
    strcat(data,"&");

    strcat(data,"To=");
    strcat(data,PHONE_TO);
    strcat(data,"&");

    strcat(data,"sid=");
    strcat(data,TWILIO_ACCOUNT_SID);
    strcat(data,"&");

    strcat(data,"token=");
    strcat(data,TWILIO_TOKEN);
    strcat(data,"&");

    strcat(data,"Body=");
    const char TEXT_MESSAGE_BODY []  = "temperature", temperature;
    strcat(data,TEXT_MESSAGE_BODY);

    wifi.httpPost("iot-https-relay.appspot.com","/twilio/Messages.json",data);

temperature should be getting sensor raw data and paste it after the "temperature" but it is not working.


texts: How do I deal with this Arduino IDE installation error?

texts:
I am using Linux Fedora 20 (yes I am going to upgrade it, definitely, soon) and I have installed arduino-1.8.0, but I get this message ...

  Your copy of the IDE is installed in a subfolder of your sketchbook.
  Please move the IDE to another folder

... when I click on the desktop icon, or run ./arduino. I have tried moving the tar.xz file to its own folder ArduinIDE again installed it but get the same message. Please,what should I do to get out of this? Please no answers like "just do what it says":in that case what do I move, and what criteria does the destination need to have?


texts: How to modify Arduino boards.txt to support new MCUs

texts:
In this post, it was mentioned that to get the Arduino IDE to support an ATmega328 (only the ATmega328P is supported):

  I should mention the Arduino way of doing this, is to create a new
  boards.txt file with this chip and add (not change) the avrdude.conf
  file. This will allow programing either from selecting the correct
  board. but that is another subject.

After a great deal of research in the past, and attempted modifications to boards.txt and avrdude.conf, I arrived at the conclusion that the Toolchain doesn't support the ATmega328 therefore the changes will have no effect.

Can anyone confirm that they have successfully found a way to make these changes, so we can avoid the need for a work-around?


texts: Fast I2C communication between ESP8266 & PCF8591

texts:
I need faster communication between the ESP and the ADC, so I found this
https://github.com/pasko-zh/brzo_i2c.

Original wire Example

#include "Wire.h"
#define PCF8591 0x48
byte a0;

void setup() {
  Wire.begin(13, 14);
  Serial.begin(115200);
}

void loop() {
  Wire.beginTransmission(PCF8591);
  Wire.write(0x04);
  Wire.endTransmission();
  Wire.requestFrom(PCF8591, 5);

  a0 = Wire.read();
  a0 = Wire.read();

  Serial.println(a0);
  delay(1000);
}

Brzo I2C example

#include "brzo_i2c.h"

uint8_t buffer[10];
uint8_t error = 0;
float temp = 0.0;

uint8_t ICACHE_RAM_ATTR get_temp(float *t) {
  uint8_t bcode = 0;
  brzo_i2c_start_transaction(0x48, 400);
  buffer[0] = 0x04;
  brzo_i2c_write(buffer, 1, false);
  brzo_i2c_read(buffer, 2, false);
  bcode = brzo_i2c_end_transaction();
  *t = ((buffer[0] << 8) | buffer[1]);
  return bcode;
}

void setup() {
  delay(500);
  Serial.begin(115200);
  brzo_i2c_setup(13, 14, 2000);
}

void loop() {
  error = get_temp(&temp);
  if (error == 0) {
    Serial.print("Temp = ");
    Serial.println(temp, 8);
  } else {
    Serial.print("Brzo error : ");
    Serial.println(error);
  }
  delay(500);
}

But I get always the same error.

  1 : Bus not free

I rewrote it in different ways, changing the frequency, pins and doing multiple transactions. The main reason I don't get it to work is the difference in the API.

There is no Wire.requestFrom(); in the brzo_i2c lib. So I need to read the value with brzo_i2c_read(buffer,2,false);.


texts: Arduino Wire.h library: how to communicate with an LCD?

texts:
I am having an Arduino Uno and a C2042A LCD with I2C shield on it. Because the VirtualWire library does not work for me. I tried only the wire library but it's still not working:

My code:

#include <Wire.h>

void setup() {
  Wire.begin(0x63);
}

void loop() {
  Wire.write(4);
}

I just read on this website which commands you have to use but it doesn't do anything. What is my fault, how to solve it?


texts: Arduino Keyboard - print() works but println() does not

texts:
I am recently seeing strange behavior in my Arduino Yun.

Just using the microcontroller, I enter the following:

#include <stdlib.h>
#include <string.h> // For string operations.
#include "Keyboard.h"
#include "Mouse.h"

void setup() {
  Keyboard.begin();
  Keyboard.println("Hello world.");
  Keyboard.print("Hello world.");
}

Rather than getting two lines as expected, I get Hello world.Hello world..

It is a very strange error because println (docs) is so 'core' to Keyboard function. I've never had this issue before and I've been playing with it for months. I am running IDE 1.6.11.

A possibly relevant detail

I had this working on my Yun months ago without the #include "Keyboard.h" and #include "Mouse.h". I opened the IDE again just recently and, upon compiling, it failed saying I needed to add those lines. So I did, and it now println doesn't work.


texts: What changes I have to take care while coding from Atmel Studio instead of Arduino IDE?

texts:
-Are there any changes in Bootloader?
-Why is the coding different for same chip in different softwares?
-How to upload the program from Atmel Studio?


texts: Windows 10 does not recognize Arduino Leonardo

texts:
Using Arduino Leonardo, IDE 1.8.9, Windows 10.

For a short time, when I first got the Leonardo, Windows 10 would recognize the board; I could see it in devices, Windows 10 would make a sound when plugged in, it would show listed in the ports of the IDE, and I could upload my code to the board (confirmed with blinking light sketch). It no longer does.

The error I get in the IDE avrdude: butterfly_recv(): programmer is not responding.

I believe the main issues stems from I had selected Arduino UNO (I have a couple of those as well) in the IDE and Uploaded my sketch.

Ever since I did this, Windows 10 no longer recognizes the board when plugged in. It doesn't even show in "other devices" under device manager.

I have tried the following:

The on-board reset trick that seems to be most of what other users experience and solves their issue. All variations. Holding the reset button, uploading, releasing, etc.
Swapping cables. Confirmed with another device it was a data cable and working.
Uninstalling and reinstalling the IDE
Restarting numerous times
Burning boot loader - since Windows 10 won't recognize the device, this fails immediately can't even communicate to the board.

I have seen similar questions about this, but none of them seem to specifically cover what I am encountering.


texts:
I saw the Web client Example  , In the example, the server connection is initialized in setup(). But I want the server to update the text file every time. So, I need the server connection to be in loop().

But, it is not working. Where is the problem in my code.

#include <GSM.h>

#define PINNUMBER ""

// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password

// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;

// URL, path & port (for example: arduino.cc)
char server[] = "yourdomain.com";
char path[] = "/current.txt";

int port = 80; // port 80 is the default for HTTP

void setup() {
// initialize serial communications and wait for port to open:
Serial.begin(9600);
Serial.println("SMS connected");

// connection state
boolean notConnected = true;

// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with the APN, login and password
while(notConnected) {
   if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
    (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
    notConnected = false;

else {
     Serial.println("Not connected");
     delay(1000);
    }
   }
Serial.println("GPRS connected...");
Serial.println(" Connecting to Server ");
}

void loop() {
if (client.connect(server, port)) {
  client.print("GET /current.txt");
  Serial.print("GET /current.txt");
  client.println(" HTTP/1.1");
  Serial.println(" HTTP/1.1");
  client.println("Host: www.yourdomain.com");
  Serial.println("Host: www.yourdomain.com");
  client.println("User-Agent: Arduino");
  Serial.println("User-Agent: Arduino");
  client.println("Accept: text/html");
  Serial.println("Accept: text/html");
  client.println("Connection: close");
  Serial.println("Connection: close");
  client.println();
  Serial.println();
  Serial.println("\nCOMPLETE!\n");
  //client.stop();

} else {
  Serial.println("connection failed");
  Serial.println("\n FAILED!\n");
}

if (client.available()) {
  char c = client.read();
  Serial.print(c);

} else {
  Serial.println();
  Serial.println("disconnecting.");
  client.stop();
}
}


texts: Steppers only vibrate, not rotate with I2C

texts:
The goal of my project is to be able to control two steppers with 4 buttons. Steppers are connected to Adafruit Motor shield(the older one) which is stacked on Arduino UNO, buttons are connected to Arduino NANO. I'm using I2C between the two Arduinos. However, if I push a button, the steppers won't rotate, only vibrate, but if I'm using only Arduino UNO with the motor shield stacked on it, button connected directly to the motor shield, it's working well.
Arduino UNO is Master Reader, while NANO is Slave Writer. There is a fritzing image of the circuit.
I don't know where's the problem, if it's in the circuit, if it's because of my battery(i bought it like 10 minutes ago) or the code. Any help is apreciated.

Master code:

#include <Wire.h>
#include <AFMotor.h>
//define steppers
AF_Stepper motor1(48, 2);
AF_Stepper motor2(48, 1);

//define variables
int x = 0;
int y = 0;

void setup()
{
  Wire.begin(5); //begin i2c communication
  Wire.onReceive(receiveEvent);
  motor1.setSpeed(200);  // 10 rpm
  motor2.setSpeed(200);  // 10 rpm

  motor1.release();
  motor2.release();
  delay(1000);
}

void loop()
{
  delay(500); // wait 0.5 second
}

void receiveEvent(int howMany)
{
    //read x,y from slave
    x = Wire.read();
    y = Wire.read();

    if (x == 1) //stepper1 rotate forward
    {
      motor1.step(100, FORWARD, SINGLE);
    }
    else if (x == 2) //stepper1 rotate backward
    {
      motor1.step(100, BACKWARD, SINGLE);
    }
     else if (y == 1) //stepper2 rotate forward
    {
      motor2.step(100, BACKWARD, SINGLE);
    }
     else if (y == 2) //stepper2 rotate backward
    {
      motor2.step(100, BACKWARD, SINGLE);
    }
}

Slave code:

#include <Wire.h>

//define buttons
const int button1 = 2;
const int button2 = 3;
const int button3 = 8;
const int button4 = 7;

//define state of buttons
int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;

//define variables
int x = 0;
int y = 0;

void setup()
{
   //start i2c communication
   Wire.begin();
}

void loop()
{
  //read state of buttons
  buttonState1 = digitalRead(button1);
  buttonState2 = digitalRead(button2);
  buttonState3 = digitalRead(button3);
  buttonState4 = digitalRead(button4);

    //if button1 is pressed,send x to master
    if(buttonState1 == HIGH){
      x = 1;
      Wire.beginTransmission(5);
      Wire.write(x);
      Wire.endTransmission();
    }
    //if button2 is pressed,send x to master
    else if(buttonState2 == HIGH)
    {
      x = 2;
      Wire.beginTransmission(5);
      Wire.write(x);
      Wire.endTransmission();
    }
    //if button3 is pressed,send y to master
    if(buttonState3 == HIGH){
      y = 1;
      Wire.beginTransmission(5);
      Wire.write(y);
      Wire.endTransmission();
    }
    //if button4 is pressed,send y to master
    else if(buttonState4 == HIGH)
    {
      y = 2;
      Wire.beginTransmission(5);
      Wire.write(y);
      Wire.endTransmission();
    }
}


texts:
I was following a tutorial on YouTube to build a Bluetooth car with Arduino.
#include <AFMotor.h>

//initial motors pin
AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor4(4, MOTOR34_1KHZ);

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;
    case 'S':
      stop();
      break;
    }
  }
}

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

void back()
{
  motor1.setSpeed(255); //Define maximum velocity
  motor1.run(BACKWARD); //rotate the motor anti-clockwise
  motor4.setSpeed(255); //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
  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 clockwiseclockwise
  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 buttonbutton
  motor4.setSpeed(0); //Define minimum velocity
  motor4.run(RELEASE); //stop the motor when release the button
}

Here's the schematic:

I didn't use the resistor, I used 4 aa batteries, and I used 2 motors instead of 4, but the bluetooth module is flashing.


texts: Connecting multiple led strips in parallel with arduino

texts:
I am making a led panel using led strips. Each of the two led strips are 5M long containing 300 LED SMD Striplights. I have cut each of the 2 strips into many small strips of lengths of about 38 cm and connected them in parallel i.e there is  a singe pair of terminals for all the strips.I have a 12V,5A power supply. I had tried to drive the panel using Arduino Mega in combination with a MOSFET as is it is commonly done for a single led strip but I am unable to make it work.
Can anybody please help me out?

Other components being used are - PIR sensor , RTC module


texts: How useful could the Arduino Yun be in computer vision in a robotics project?

texts:
I've recently ordered an Arduino Yun and several other components to begin on a small robotics project (based on an old 4x4 RC Truck).  Although not mandatory for what I'd like to do, I was wondering how feasible it would be to mount a small camera or two and write some software for the Linux portion of the Yun to do basic image/video analysis such as face detection and computer vision based path finding?

Mostly this is a question about the processing power capabilities of the Yun.  Has anyone had any luck doing simple image analysis/recognition on this processor?

(Also, if anyone with 150+ rep could edit this to create and add the "computer-vision" tag that would be great)


texts: How do you configure ADC7 on the Arduino Pro Mini as a digital output?

texts:
I'm attempting to use the pin labeled 'ADC7' from the Atmega328p TQFP package. The Atmega documentation suggests that can be used either as an analog or digital I/O point. I'm trying to configure it as a digital output.

Referencing the documentation (and specifically arduino_pins.h), I determined the associated pin number was 21. Thus I called pinMode(21, OUTPUT). However, this pin does not appear to be working with my SPI device. I previously tested that the device worked, but I made a last second change of pin and am now using ADC7.

So my question, is there an additional step required to configure this pin as a digital output? I noticed that this pin doesn't exist on the DIP Atmega328p (used on the Arduino Uno), so I'm not sure if I have to add another line of code somewhere.

Any ideas?

Regards,


texts:
I have a Question regarding Arduino IDE:

Many old Arduino setup examples states that the Serial.begin() function always should begin with :

Serial.begin(9600); // (or 115200)

while (!Serial)
 {
   ; // Wait for serial to connect
 }

Now I have read a lot of comments saying that this "Wait-function" is no longer necessary ??

Is this an old routine, that's no longer necessary, or is it still important ???


texts: Statistical Mode calculation in Arduino programme

texts: How can I calculate the statistical mode from a set of values obtained from a distance sensor in an Arduino programme?


texts:
I'm trying to make a traffic light system with a ultrasonic range sensor as well as a light dependant resistor. I'm trying to make it so that the default setting is 2 seconds red light 1 second yellow 2 seconds green then 1 second yellow, this will then repeat until something else happens - I've got this working fine.

Then I want 2 different states.

One where if something comes with 10cm of the sensor then the buzzer will beep and the yellow light must blink on and off 10x with intervals of 0.1ms. When the object moves away it must then return to the default setting.

Secondly I want it when the LDR detects that the light has dropped below a level the red light will turn on and stay on until a object approaches the sensor. When an object is near the sensor it must then turn the red light off and turn the Green light on.

Here is all the code i have so far and i cant figure out why its not working.
Any help would be appreciated
Thanks

    #define ECHOPIN 3
    #define TRIGPIN 2
    float distance;
    long distancecm;

    int RED = 13;
    int YELLOW = 12;
    int GREEN = 11;

    int piezoPin = 8;

    int sensorpin = A0;
    int sensorvalue = 0;

    void setup() {
      pinMode(RED, OUTPUT);
      pinMode(YELLOW, OUTPUT);
      pinMode(GREEN, OUTPUT);
      Serial.begin(9600);
      pinMode(ECHOPIN, INPUT);
      pinMode(TRIGPIN, OUTPUT);
      }

    void distancesensor()
      {
      digitalWrite(TRIGPIN, LOW);
      delayMicroseconds(2);
      digitalWrite(TRIGPIN,HIGH);
      delayMicroseconds(10);
      digitalWrite(TRIGPIN,LOW);
      distance = pulseIn(ECHOPIN, HIGH);
      distancecm = distance/29.1/2;
      if (distancecm <=10);
        for (int j=1; j<=5; j=j+1)
        {
         tone(piezoPin, 1, 500);
         digitalWrite(YELLOW, HIGH);
         delay(100);
         break;
         }
    }

    void lightsensor()
      {
      sensorvalue = analogRead(sensorpin);
      if (sensorvalue > 500)
        digitalWrite(RED,HIGH);
        digitalWrite(TRIGPIN, LOW);
        delayMicroseconds(2);
        digitalWrite(TRIGPIN,HIGH);
        delayMicroseconds(10);
        digitalWrite(TRIGPIN,LOW);
        distance = pulseIn(ECHOPIN, HIGH);
        distance = distance/58;
        while (distance >10)
          digitalWrite(RED,LOW);
          digitalWrite(GREEN,HIGH);
          digitalWrite(TRIGPIN, LOW);
          delayMicroseconds(2);
          digitalWrite(TRIGPIN,HIGH);
          delayMicroseconds(10);
          digitalWrite(TRIGPIN,LOW);
          distance = pulseIn(ECHOPIN, HIGH);
          distance = distance/58;

       }

    void loop() {
      distancesensor;
      lightsensor;
      digitalWrite(RED, HIGH);          //RED ON
      delay(2000);                      //WAIT 2 SECONDS
      digitalWrite(RED, LOW);           //RED OFF
      delay(200);
      distancesensor;
      lightsensor;
      digitalWrite(YELLOW, HIGH);       //YELLOW ON
      delay(1000);                      //WAIT 1 SECOND
      digitalWrite(YELLOW, LOW);        //YELLOW OFF
      delay(200);
      distancesensor;
      lightsensor;
      digitalWrite(GREEN, HIGH);        //GREEN ON
      delay(2000);                      //WAIT 2 SECONDS
      digitalWrite(GREEN, LOW);         //GREEN OFF
      delay(200);
      distancesensor;
      lightsensor;
      digitalWrite(YELLOW, HIGH);       //YELLOW ON
      delay(1000);                      //WAIT 1 SECOND
      digitalWrite(YELLOW, LOW);        //YELLOW OFF
      delay(200);
      distancesensor;
      lightsensor;
      //REPEAT
      }


texts: Emergency stop button for arduino mega code and circuit attached

texts:
I am trying to control steppers with pushbuttons and sensors.I want to add one more Pushbutton so that I can press it to stop the circuit and code running if something goes wrong in between.
Below is the code I am using to run the steppers:

int dirpin_T1 = 26;
int dirH_T1 = 28;
int steppin_T1 = 30;
int dirpin_F1 = 5;
int dirH_F1 = 6;
int steppin_F1 = 7;

int PB17ACW = 23;
int PB17ACCW = 22;
int PB17BCW = 25;
int PB17BCCW = 24;

int S01 = 34; // SENSOR INPUTS
int S02 = 35;
int S03 = 36;
int S04 = 37;

void setup()
{
  pinMode(dirpin_T1, OUTPUT);
  pinMode(dirH_T1, OUTPUT);
  pinMode(steppin_T1, OUTPUT);
  pinMode(dirpin_F1, OUTPUT);
  pinMode(dirH_F1 , OUTPUT);
  pinMode(steppin_F1, OUTPUT);

  pinMode(PB17ACW, INPUT_PULLUP);
  pinMode(PB17ACCW, INPUT_PULLUP);
  pinMode(PB17BCW, INPUT_PULLUP);
  pinMode(PB17BCCW, INPUT_PULLUP);

  pinMode(S01, INPUT);
  pinMode(S02, INPUT);
  pinMode(S03, INPUT);
  pinMode(S04, INPUT);
}

void loop()
{
  if (digitalRead(PB17ACW) == LOW &&  digitalRead(PB17ACCW) == LOW)
  {
    // STOP MOTOR WHEN NO KEY PRESSED
  }

  // FOR FORWARD ROTATION
  if (digitalRead(PB17ACW) == HIGH &&  digitalRead(PB17ACCW) == LOW )
  {
    digitalWrite(dirpin_T1, LOW );     // Set the direction.
    digitalWrite(dirH_T1, LOW);
    delay(1000);

    for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
    {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    }

    digitalWrite(dirpin_F1, LOW );     // Set the direction.
    digitalWrite(dirH_F1, LOW);
    delay(1000);
    do
    {
      digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    } while (digitalRead(S01) == LOW);

    delay(1000);

    digitalWrite(dirpin_T1, LOW );     // Set the direction.
    digitalWrite(dirH_T1, HIGH);
    delay(1000);

    for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
    {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    }
  }

  // FOR  BACKWARD ROTATION
  if (digitalRead(PB17ACW) == LOW &&  digitalRead(PB17ACCW) == HIGH)
  {
    digitalWrite(dirpin_T1, LOW );     // Set the direction.
    digitalWrite(dirH_T1, LOW);
    delay(1000);

    for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
    {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    }
    digitalWrite(dirpin_F1, LOW );     // Set the direction.
    digitalWrite(dirH_F1, HIGH);
    delay(1000);
    do
    {
      digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    } while (digitalRead(S02) == LOW);

    delay(1000);
    digitalWrite(dirpin_T1, LOW );     // Set the direction.
    digitalWrite(dirH_T1, HIGH);
    delay(1000);

    for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
    {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    }
  }
//WANT CODE TO STOP CODE ANYTIME I PRESS STOP BUTTON

}


texts: ESP32 partition table and writing location

texts:
In my ESP32 project I have the following platformio.io file:
[env:esp32-poe]
platform = espressif32
board = esp32-poe
framework = arduino
lib_deps =
    openslab-osu/SSLClient@^1.6.7
    knolleary/PubSubClient@^2.8
    bblanchon/ArduinoJson@^6.16.1
monitor_speed = 115200

[env:custom_builtin_table]
board_build.partitions = default.csv

the default.csv table is this one:
# Name,   Type, SubType, Offset,  Size, Flags
nvs,      data, nvs,     0x9000,  0x5000,
otadata,  data, ota,     0xe000,  0x2000,
app0,     app,  ota_0,   0x10000, 0x140000,
app1,     app,  ota_1,   0x150000,0x140000,
spiffs,   data, spiffs,  0x290000,0x170000,

I noticed that when I upload the code to my ESP32 the output is like this:
[...]
Configuring flash size...
Auto-detected Flash size: 4MB
Compressed 17104 bytes to 11193...
Writing at 0x00001000... (100 %)
Wrote 17104 bytes (11193 compressed) at 0x00001000 in 0.3 seconds (effective 521.5 kbit/s)...
Hash of data verified.
Compressed 3072 bytes to 128...
Writing at 0x00008000... (100 %)
Wrote 3072 bytes (128 compressed) at 0x00008000 in 0.0 seconds (effective 5621.7 kbit/s)...
Hash of data verified.
Compressed 8192 bytes to 47...
Writing at 0x0000e000... (100 %)
Wrote 8192 bytes (47 compressed) at 0x0000e000 in 0.0 seconds (effective 27422.0 kbit/s)...
Hash of data verified.
Compressed 1003456 bytes to 585011...
Writing at 0x00010000... (2 %)
[...]

Hence, it writes at:

0x1000
0x8000
0xe000 (otadata)
0x10000 (app0)

But I cannot understand what are the first two writings.


texts: Should I try to make my sketches as small as possible, even when I have enough room?

texts:
There has been a lot of talk about shrinking sketches recently, but if you don't need the room, should it be done? Will it speed up my program?

Take this code:

int led = 13;
int val;

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

void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

  val = digitalRead(10);
}

1,396 bytes on Arduino Uno. Now let's shrink it a bit:

int led = 13;
int val;

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

void loop() {
  blink();
  val = digitalRead(10);
}

void blink() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

1,270 bytes. A 10% decrease! It could be shrunk even more. I have the space... is it more efficient (as far as speed) to make it the most compact I can or leave it "uncompressed?" I would imagine that it would be a little more work (not much) calling blink();, therefore slowing down my code. Is this true? Are there other advantages/disadvantages of making it as small as possible (besides storage/distribution of C++ files)?


texts:
I have an Arduino Uno and 3 IR led's. Each of my IR led's works fine individually if I connect them to pin 11.

However I want to connect all 3 of the led's to the Uno and have them send different signals according to pin number.

e.g

IR LED 1 connected to pin 11 - send signal 0xABCDEFGH

IR LED 2 connected to pin 10 - send signal 0xSJKLMNOP

IR LED 3 connected to pin 09 - send signal 0xZXYRWVUG

I tried making my own code below but it does not work. If anyone has any pointers i'll be very happy.

//LED 1

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 11; i++) {
            irsend.sendNEC(0xABCDEFGH, 32); //Settings Menu
            delay(1000);
        }
        delay(1000); //1 second delay
    }

//LED 2

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 10; i++) {
            irsend.sendNEC(0xSJKLMNOP, 32); //HDMI Port
            delay(1000);
        }
        delay(1000); //1 second delay
    }

//LED3

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 9; i++) {
            irsend.sendNEC(0xZXYRWVUG, 32); //Switch Off Monitor
            delay(1000);
        }
        delay(1000); //1 second delay
    }


texts: WindowsError(31, 'A device attached to the system is not functioning.') in arduino

texts:
Having board esp32 devkit v1, to get started with arduino ide (installed recommended boards for esp32) I marked board asDOIT ESP32 DEVKIT V1 (as no other options as like ESP32 DEVKIT V1 ) so upload gets this error

    esptool.py v2.6
Serial port COM3
Traceback (most recent call last):
File "esptool.py", line 2959, in <module>
File "esptool.py", line 2952, in _main
File "esptool.py", line 2652, in main
File "esptool.py", line 222, in __init__
File "site-packages\serial\__init__.py", line 88, in serial_for_url
File "site-packages\serial\serialwin32.py", line 62, in open
serial.serialutil.SerialException: could not open port 'COM3': WindowsError(31, 'A device attached to the system is not functioning.')
Failed to execute script esptool
the selected serial port Failed to execute script esptool
 does not exist or your board is not connected

so how do I upload my programs?
I would be highly obliged if you could please help me solve this problem.
Thank you.


texts: Getting incorrect output from ADC over SPI in Arduino Uno

texts:
I am trying to read data from an ADC ADCS7476 (datasheet) using SPI on Arduino Uno. I am using the following code to read the data from the ADC and printing it on serial monitor. However, the code is always printing 0. I never used SPI before and I am not able to debug the issue, does anyone know where I am going wrong.

I am using the following connections:

ADC's SCLK to Pin 13 on Ardunio
ADC's SDATA to Pin 12 on Arduino
ADC's CS to Pin 10 on Arduino

Code:

#include <SPI.h>
#define cs 10

SPISettings settingsA(250000, MSBFIRST, SPI_MODE0);
byte highbyte,lowbyte;
unsigned int data;

void setup() {
  Serial.begin(9600);
  pinMode(cs, OUTPUT);
  digitalWrite(cs, HIGH);
  delay(1000);
  SPI.begin();
}

void loop() {
  SPI.beginTransaction(settingsA);
  digitalWrite(cs, LOW);
  delayMicroseconds(1);
  highbyte = SPI.transfer(0xFF);
  lowbyte = SPI.transfer(0xFF);
  digitalWrite(cs, HIGH);
  delayMicroseconds(1);
  SPI.endTransaction();
  data= ((unsigned int)highbyte << 8 ) + lowbyte;
  Serial.println(data);
  delay(100);
}


texts: Issue with Visual Studio not seeing arduino boards

texts: Below is a screenshot. I used Visual Studio with the Visual Micro [arduino extension] a few months back. I switched computers and installed Visual Studio on the new one but for some reason after Visual Micro has been installed its not seeing any of the boards. In the visua lMicro explorer it doesnt have an option for the board manager. If anyone can point me in the right direction that would be great.


texts: Error with libraries after setting up Code::blocks to work as an arduino IDE

texts:
I followed this guide: http://arduinodev.com/guide-to-arduino-development-environment-codeblocks/

Everything seemed to work until I compiled the example code:

#include <Arduino.h>

/*
  Turns on an LED on for one second, then off for one second, repeatedly.

  This example code is in the public domain.
*/

void setup()
{
    // initialize the digital pin as an output.
    // Pin 13 has an LED connected on most Arduino boards:
    pinMode(13, OUTPUT);
}

void loop()
{
    digitalWrite(13, HIGH);   // set the LED on
    delay(1000);              // wait for a second
    digitalWrite(13, LOW);    // set the LED off
    delay(1000);              // wait for a second
}

and it gave me this errors:

||=== Build: Simulator - Debug in test (compiler: GNU GCC Compiler) ===|
/home/meneses/.codeblocks/ardusim/include/util/delay.h|90|warning: #warning "Compiler optimizations disabled; functions from <util/delay.h> won't work as designed" [-Wcpp]|
/usr/include/x86_64-linux-gnu/sys/types.h|197|error: conflicting declaration ‘typedef long int int64_t’|
/home/meneses/.codeblocks/ardusim/arduino/cores/stdint.h|33|error: ‘int64_t’ has a previous declaration as ‘typedef long long int int64_t’|
/usr/include/unistd.h|267|error: conflicting declaration ‘typedef __intptr_t intptr_t’|
/home/meneses/.codeblocks/ardusim/arduino/cores/stdint.h|66|error: ‘intptr_t’ has a previous declaration as ‘typedef int intptr_t’|

If I click on those errors I go to this following libraries:

first error - type.h, on line 197:

__intN_t (64, __DI__);

second error: stdint.h, on line 33:

typedef long long  int64_t;

third error: unistd.h, on line 267:

typedef __intptr_t intptr_t;

forth error: stdint.h, on line 66:

typedef int intptr_t;

And there's also the warning, on the delay.h library, line 90:

# warning "Compiler optimizations disabled; functions from <util/delay.h> won't work as designed"

How can I fix this?

Thank you!

edit: I've also found this error if instead of running the simulation debugger I run arduino UNO for example:

library features.h, line 374, error:

fatal error: sys/cdef.h: No such file or directory

But none of the other errors above..

The line is: #  include <sys/cdefs.h>

Edit2: solved the previous error by running this command:
sudo apt-get install libc6-dev-i386

but now I'm running into 'uint_farptr_t' was not declared in this scope, I'll try to solve them.

edit3: fixed the previous item by going into code::block's settings -> compiler -> selected compiler -> GNU GCC compiler for AVR -> Search directories -> Compiler -> remove /usr/include

I don't know the consequences of this, but it fixed that error.

Now I'm getting 5 errors of this type:

/home/meneses/.codeblocks/arduino/hardware/arduino/cores/arduino/HardwareSerial.cpp|91|error: attempt to use poisoned "SIG_USART0_RECV"|

edit4: I feel like cryinggg

edit5: I'm now willing to install other IDE, all I want is to be able to run simulations.

I'm using Linux Mint 17.3.


texts: What is the use of 1k resistor shown in the picture and why it is used? Please check Arduino Uno Schematics for more info

texts:
Can anyone tell me why 1k resistor is used on pin 13 of ATmega16U2 in arduino uno schematics. I have also seen a 100k resistor used in this position?

Link for schematics - https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf


texts: Why do I get avrdude: stk500v2_ReceiveMessage(): timeout error when uploading to Arduino Mega?

texts:
I have an Arduino Mega clone and I haven't used it for a while. I remember it not working so when I plugged it in and tried uploading the code to it and sure enough it didn't work. So I plugged in an Uno and it worked. The Mega is a 2560 Atmel. Here's my code:

#define distanceForward A0
#define distanceLeft A1
#define distanceRight A2
#define distanceRightAngle A3
#define distanceLeftAngle A4
#define distanceBack A5
int talk = 2;

void setup() {
  Serial.begin(9600);
  pinMode(talk, OUTPUT);
  pinMode(distanceForward, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Front Facing
  pinMode(distanceLeftAngle, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Left Angle
  pinMode(distanceRightAngle, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Right Angle
  pinMode(distanceLeft, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Left
  pinMode(distanceRight, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, Right
  pinMode(distanceBack, INPUT);
  // /\ Ir distance sensor pin for input signal to arduino, back
}

void hall_roam() {
  Serial.write("forward");
  if (analogRead(distanceLeftAngle) < 30) {
    Serial.write("right");
    if (analogRead(distanceLeftAngle) > 30) {
      Serial.write("forward");
    }
    if (analogRead(distanceRightAngle) < 30) {
      Serial.write("left");
      if (analogRead(distanceRightAngle) < 30) {
        Serial.write("forward");
      }
      if (analogRead(distanceForward) < 60) {
        Serial.write("stop");
        if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
          Serial.write("left");
          if (analogRead(distanceForward) > 60) {
            Serial.write("stop");
          }
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) > 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      }
      if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) > 60)) {
        Serial.write("right");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
        }
      } else {
        Serial.write("forward");
      }
    }
  }
}

void roam() {
  Serial.write("forward");
  if (analogRead(distanceForward) < 60) {
    Serial.write("stop");
    Serial.write("left");
    if (analogRead(distanceForward) > 60) {
      Serial.write("stop");
      Serial.write("forward");
    }
  }
}

void talkbb8() {
  pinMode(talk, HIGH);
  pinMode(talk, LOW);
}

void chill() {
  Serial.write("stop");
  talkbb8();
}

void loop() {
  if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
    hall_roam();
  } else if ((analogRead(distanceForward) < 60) && (analogRead(distanceBack) < 60)) {
    Serial.write("left");
    if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
      Serial.write("stop");
      hall_roam();
    }
  } else {
    roam();
  }
}

If there's a bracket out of place or something it's probably nothing. I'm talking about the characters. Is there anything in the characters that would screw up the upload like the three "!!!" problem I heard about or something like that. It's possible that the USB chip in it isn't recognized by my iMac. If so how do I fix that?


texts:
Hi we are using an Arduino Micro and working with a Bluetooth device and a Rfid Scanner from Sparkfun(ID-20 LA). For that we implemented 2 SoftwareSerial objects and the Serial port for the Serial Monitor. If we use one SoftwareSerial object and the normal Serial everything works fine. For example we can send and receive things over Bluetooth. But when adding another SoftwareSerial object( Rfid then ) One of them doesn't work.

Starting with the Rfid SoftwareSerial ends up to the same result.

We've also already tried to change the ports and so one.

Every help is appreciated.
Thanks in advance.

The Code ( this is already the third programm nothing has changed )

#include <SoftwareSerial.h>

SoftwareSerial rf(11, 12);
SoftwareSerial bt(8,9);

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

}

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

   Serial.println("");
  }

  if(rf.available())
  {
   while(rf.available())
     Serial.write(rf.read());

   Serial.println("");
  }

  if(bt.available())
  {
   while(bt.available())
     Serial.write(bt.read());

   Serial.println("");
  }
}


texts:
I'm trying to interface with version RM08S of this rotary encoder using an Arduino Mega. The sensor supports a "Synchro serial interface (SSI), single ended" interface. I'm unfamiliar with this protocol.

Despite the name, it doesn't appear to match the description of the formal SSI or RS-422 specification, since that requires two wires for differential clock and data lines, whereas this sensor only has a single wire for each. This makes it sound more like IIC, but without the bus-like functionality.

Googling finds very few results on interfacing the Arduino to SSI devices, much less any standard libraries. This forum thread asks a similar question, but doesn't seem to resolve the issue.

Since there's just a clock and data line, would reading from this be as simple as toggling clock, and then reading the 10-bits of data from the data line, sequentially with each clock tick, accounting for whatever bits are used to pad the packet?


texts: Receiving garbled `char` array returned by a function

texts:
I return a char[300] array from a function.  If I intialize a char* variable with it, the return is garbled, but not if I append it to a String.  What gives?

  const char* post2 =  uploadHourCsv(timeNow,pulseChangeHour) ;
  String postS2 = "";
  postS2 =  uploadHourCsv(timeNow,pulseChangeHour) ;
  //const char* post2 = { uploadHourCsv(timeNow,pulseChangeHour) };
  if( debug ) {
    Serial.print("received in loop() as : [");
    Serial.println(post2);
    Serial.print("String : [");
    Serial.println(postS2);
  }

...

char postStr[300] = "";
// populate array
if( debug ) {
  Serial.print("postStrCsv generated: ");
  Serial.println(postStr);
}
return postStr;

  postStrCsv generated: 00000003;3|  0.00;8|17.55;9|17.55;10|18.12;11|16.92;20|93817;22|93789;101|6;time|1559646000;

  received in loop() as : [000?⸮@⸮⸮?" ⸮⸮?17.55;9|17.58! @0⸮⸮⸮⸮G% @5~`⸮h⸮?⸮⸮

  String : [00000003;3|  0.00;8|17.55;9|17.55;10|18.12;11|16.92;20|93817;22|93789;101|6;time|1559646000;


texts: Arduino slave with 2 masters sharing the same I2C Bus?

texts:
Consider a scenario where two (or more) master devices (the NodeMCU's, in this case) share an I2C bus with one (or more) slave device(s), like thus:

Would this be a feasible setup?  In other words,  could both masters request (not simultaneously) from the slave?


texts:
After asking How to connect Arduino & ESP8266, I tried to build such circuit.
First I tried the code one 2 Nano's - to verify 2 MCU sending and receiving messages. After that, I started to build the following circuit:
Take1: MCU A: Arduino Micro 5V, MCU B: WEMOS mini. R1=10K, R2=20K. FAIL
Take2: MCU A: Arduino Micro 5V, MCU B: WEMOS mini. R1=1K, R2=2K. FAIL
Take3: MCU A: Arduino NANO ,MCU B: WEMOS mini. R1=1K, R2=2K. FAIL
Take4: MCU A: Arduino NANO 5V, MCU B: WEMOS mini. Tx to Rx (no vdiv ). OK

Edit1: LCD display is connected to MCU B ( as it was tested using 2 Nano ) via I2C. Messages received are sent to LCD. PLEASE IGNORE LCD shown in not I2C
Edit2:

Diagram updated - GND was missing and POWER IN clarification.

LCD display is an I2C one. It shows properly WEMOS is booting up properly ( shows a boot msg ), and spits every incoming Serial message from other MCU. When TAKE4 and TAKE1 were taken, setup and code worked PROPERLY.

What is done wrong?


texts: How can I connect multiple different sensors that uses the same pins?

texts:
I'm doing a project on Arduino Uno and it requires me to connect 3 different sensors together: Waveshare 2.9 E-paper, MFRC522 RFID Reader and a ESP8266 wifi module. problem is, The e-paper and RFID uses the same multiple digital pins. How can I connect all of them together in a beardboard?

Edit:
The E-Paper uses:

e-paper 3V3 -> Arduino 3V3
e-paper GND -> Arduino GND
e-paper DIN -> Arduino D11
e-paper CLK -> Arduino D13
e-paper CS -> Arduino D10
e-paper DC -> Arduino D9
e-paper RST -> Arduino D8
e-paper BUSY -> Arduino D7

The rfid uses:

SDA --> Digital 10
SCK --> Digital 13
MOSI --> Digital 11
MISO --> Digital 12
IRQ --> unconnected
GND --> GND
RST --> Digital 9
3.3V -->3.3V

The wifi uses:

GND --> GND
VIN --> 3.3v
Enable --> 3.3V
TX --> RX
RX --> TX

I'm very new to electronics so i'm sorry if something does not make sense

I'm using library, code and instructions from this 3 websites:

E-paper ( Waveshare 2.9 E-paper): https://www.instructables.com/id/Getting-Started-With-E-Paper-Display-Modules/

RFID (MFRC522 RFID Reader): https://randomnerdtutorials.com/security-access-using-mfrc522-rfid-reader-with-arduino/

Wi-Fi (ESP8266 wifi module): https://www.hackster.io/jeffpar0721/add-wifi-to-arduino-uno-663b9e

Thanks!


texts: Why my arduino board does not blink properly?

texts:
I have two files
blink1.cpp
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

blink2.cpp
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;
port_type portC = (port_type) 0x28;
port_type ddrC = (port_type) 0x27;
port_type portD = (port_type) 0x2B;
port_type ddrD = (port_type) 0x2A;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

The difference between these two files are the definition of only a few unused ports in blink2.
I compile and upload them to the board by
avr-g++ blink1.cpp -o blink1
avr-objcopy -O ihex -R .eeprom blink1 blink1.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink1.hex

avr-g++ blink2.cpp -o blink2
avr-objcopy -O ihex -R .eeprom blink2 blink2.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink2.hex

The first one does not blink properly but the second one does. What is the problem of the first code?


texts:
I have following problem:
I'm reading 8 bit signal from one Arduino pin and store all informatin in bool array. Now I want to convert this array to single byte in decimal. How to do this?

I've tried this:

bool ID[8] = {0, 0, 0, 0, 0, 0, 1, 1};
int recivedID = int(ID);

and

bool ID[8] = {0, 0, 0, 0, 0, 0, 1, 1};
int recivedID = ID.toInt();

non works.


texts:
I am trying to run two stepper motor at same time with different RPM.
I decided to use two rotary encoder for change the RPM separately.

But,
I am in problem with driving stepper at same time due to the delay time of the step pulse.

How can I generate separate(different duty cycle) step pulses for stepper motors? It's the main problem that I faced.

I have used some Arduino libraries and all of that library has same system for step pulse generation. But, I couldn't understand those well.

void AH_EasyDriver::setSpeedRPM(long RPM)
{
   float DIV = RPM*this->MOTOR_RESOLUTION;
    this->STEP_DELAY =  60000000.0L/DIV;
 }

This function calculate the step time for given specific RPM

void AH_EasyDriver::move(int NUMBER_OF_STEPS)
{
   while(STEPS > 0) {
    if (micros() - this->LAST_STEP_TIME >= this->STEP_DELAY) {
      this->LAST_STEP_TIME = micros();
      STEPS--;
      stepMotor();
}
}

}

This function rotate the motor the motor in STEP_DELAY using stepMotor() function.

void AH_EasyDriver::stepMotor()
{
  digitalWrite(this->STEP_pin, HIGH);
  delayMicroseconds(100);
  digitalWrite(this->STEP_pin, LOW);
  delayMicroseconds(100);
}

This function makes CONSTANT step pulses.

I removed some lines in the function. This is the link for original .cpp file.
All of stepper controlling libraries has this functions.
I couldn't understand how this functions can change the RPM. Can someone explain this?


texts: Is there any way to run Arduino sketches on Raspberry Pi (basically on Raspbian)? I have several projects that work on Arduino and I would like to run the exact same stuff on my Raspberry Pi. Is there a way to just put all the pins off the Arduino, put them on the Raspberry, then adjust the pin number settings in the Arduino sketch, and then run the program on Raspberry?


texts: why are there odd spikes in the USB serial data transfer rates?

texts:
I'm trying to use an Arduino for data collection, and hoping to get a consistent sampling rate.

I looked into the serial communication using the simplest program I could, but it produces odd results.

void setup() { Serial.begin(9600); }
void loop() { Serial.println("00000"); }

I use a python script to read the data and create a text file and write the time in seconds before the five zeros.

Using the seconds as a marker, I then count the number of data lines for each second.  for example:

44 00000  // recorded at time 44 seconds
44 00000
44 00000
45 00000  // recorded at time 45 seconds, etc

I was expecting that there would be a somewhat stable value for this.  Using 10 bits per character, printing the 5 zeros should be able to be done about 190 times per second.  When analyzed, it turns out to be lower, which isn't surprising due to overhead, but also unexpectedly variable.

Collecting the zeros for 5000 seconds produced the following results:
most often, there were 137 sets of 00000 collected per second, followed by 138 sets of 00000.  This is easily explainable by not being equally spaced per second, and having one second with 137 followed by one second with 138.

What is harder to explain is when it jumps to 139, 140, 141 and 142 sets of 00000 per second.

Out of the 5000 seconds of data, there were 25 seconds where 140 sets of 00000 were created.  That isn't too bad and could be due to timing.

But, out of the 5000 seconds, there were 203 seconds where 142 sets of 00000 were created.

The percent breakdown is as follows:

137 sets of 00000:  79.15%
138 sets of 00000:  13.8%
139 sets of 00000:  0.39%
140 sets of 00000:  0.51%
141 sets of 00000:  2.05%
142 sets of 00000:  4.11%

the first 4 could be explainable with minor timing errors, the last ones are very hard to explain.  with 137 sets of 00000 there are 685 characters sent serially in one second.

with 142 sets of 00000 there are 710 characters sent serially in one second.

What I am trying to figure out is why the variability is so wide and also so consistent - as in the pattern, which can be seen in the graph.

Is there any explanation for the variability?

Because of the variability in the transfer, it is very hard to sync up data or filters or other uses when a constant sample rate is needed.

I've also added delays in the main loop from 1ms to 7ms, 7ms was the maximum because that would not cause the loop to run slower than the free running speed at 142 loops/transmissions per second (1sec/7ms = 142.8 loops per second discounting all other overhead) and found the same patterns.

Using a delay of 8ms produced another interesting result:
with a delay of 8ms, most of the data was transmitted at 123 or 124 sets of 00000 per second, but every 12 seconds there would be a burst of 128 sets of characters.  this makes sense because the delays add up to less than one second for 11 loops, then get an extra loop for that second, but that adds 15 characters, not just 5.

After re-reading this, it dawned on me that there might be some loop timing/buffering errors, so instead of a delay, I used Serial.flush() to pause the loop until the data was sent.

This resulted in a free-running result of 137 sets transmitted per second for the most common, followed by 138 sets.  The new issue is that every 25 seconds there is a drop down to 133 sets of characters transmitted per second, which seems to be the same issue only causing slowing instead of speeding up.

I thought I found the answer with Serial.flush() but there is still something causing huge changes in the sent characters per second.  What could be causing this? and what can be done to make the transfer rates more constant?


texts: ESP8266 WiFiEspClient Disconnect 3 with GPS

texts:
I have recovered an old sketch (2 years ago) in which I used 2 DHT22 sensors and sent the values to an web app to store in database. The sketch works fine with a ES8266 module connected to an arduino uno. In my new project I am trying to do the same action, but sending GPS coordinates obtained with GPS NEO-6m module.
I have write a function that returns a string with the parameters as lat, lng, altitude, and others.
void loop(){
  gps_data = get_gps_data();

  // all code for wifi client sending
  ..........
  client.print("GET /reads/store?"+gps_data);
  .......
  .......
}
String get_gps_data(){
  // GPS capture function
  ...........
}

The function takes 5 second in get GPS information but I always get....
TIMEOUT>>>
Disconecting 3
and none call arrives to to web server
but if I change (for example..)
gps_data = "gps=1&lat=36.125471&lng=-4.478658.....";

the system works fine and send continuously the data, and if I put a delay before and after the gps the system works. If I take a value from DHT22, the code works too, but with the GPS the URL is not sent to the server.
Any idea?
Thank you in advance...