texts: Changing Arduino SD library SPI port on Arduino Zero (ATSAMD21G18A)

texts:
I have been trying to change the SPI port for SD library on Arduino Zero from the default (MISO: PA12, MOSI: PB10 and SCK PB11) to this: (MISO: PA19(D12), MOSI: PA16(D11) and SCK PA17(D13)).
I have found some guides on the internet most useful one being this.
After reading this I changed the variant.h for Arduino Zero to this:
/*
 * SPI Interfaces
 */
#define SPI_INTERFACES_COUNT 1

#define PIN_SPI_MISO         (34u)
#define PIN_SPI_MOSI         (35u)
#define PIN_SPI_SCK          (37u)
#define PERIPH_SPI           sercom1
#define PAD_SPI_TX           SPI_PAD_2_SCK_3
#define PAD_SPI_RX           SERCOM_RX_PAD_0

and then I wanted to the change the MUX type for the pins in variant.cpp but I got confused; At some point in the file it specifies the related pins as the following and later on as SPI pins.
Sets the MUX as TIMER and PWM here:
{ PORTA, 16, PIO_TIMER, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM2_CH0, TCC2_CH0, EXTERNAL_INT_0 }, // TCC2/WO[0]
  { PORTA, 19, PIO_TIMER_ALT, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER_ALT), No_ADC_Channel, PWM0_CH3, TCC0_CH3, EXTERNAL_INT_3 }, // TCC0/WO[3]

  // 13 (LED)
  { PORTA, 17, PIO_PWM, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM2_CH1, TCC2_CH1, EXTERNAL_INT_1 }, // TCC2/WO[1]

Then it also describes them like this:
 // 34..37 - EDBG/SPI
  { PORTA, 19, PIO_SERCOM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // MISO: SERCOM1/PAD[3]
  { PORTA, 16, PIO_SERCOM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // MOSI: SERCOM1/PAD[0]
  { PORTA, 18, PIO_SERCOM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // SS: SERCOM1/PAD[2]
  { PORTA, 17, PIO_SERCOM, PIN_ATTR_NONE, No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // SCK: SERCOM1/PAD[1]

I ended up commenting the first set out and replacing them with these lines:
 { PORTA, 16, PIO_SERCOM, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM2_CH0, TCC2_CH0, EXTERNAL_INT_0 }, // TCC2/WO[0]
 { PORTA, 19, PIO_SERCOM, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER_ALT), No_ADC_Channel, PWM0_CH3, TCC0_CH3, EXTERNAL_INT_3 }, // TCC0/WO[3]

  // 13 (LED)
  { PORTA, 17, PIO_SERCOM, (PIN_ATTR_DIGITAL|PIN_ATTR_PWM|PIN_ATTR_TIMER), No_ADC_Channel, PWM2_CH1, TCC2_CH1, EXTERNAL_INT_1 }, // TCC2/WO[1]

and didn't touch the second set.
I wanted to just change the main SPI and not add another SPI Port so I don't have to modify the SD library.
I tried these with the SD cardInfo example and it always tells me initialization failed also I have checked the SD card and module with the default SPI port and it works fine.
You can also have a look at the unmodified files here: variant.h variant.cpp


texts: Unable to obtain pulse train at 32Hz with 20us pulse width with Uno

texts:
I tried to obtain 32Hz pulse train(between 30Hz and 35Hz is also fine) with around 20us pulse width with Arduino Uno but couldn't succeed. The problem is:

If I do the following:

void setup() {

    TCCR1B = TCCR1B & B11111000 | B00000101;

    pinMode(pwmPin9, OUTPUT); // sets the pin as output

}

void loop() {

analogWrite(pwmPin9, 1)

}

I can set the freq. roughly at 30Hz but analogWrite(pwmPin9, 1) will give minimum 100us cannot go down to 20us.

digitalWrite method with delay on the other hand doesn't work to obtain frequencies below about 60Hz.

How can I obtain a pulse train output with between 30Hz to 35Hz and with around 20us pulse width?


texts: What's the difference between different Ethernet Shields?

texts:
I am working on a project with Arduino and I need an Ethernet shield. but after searching in some electronics shops I found there isn't only one but a lot. I don't know which one is better and what are the differences.

Arduino Ethernet with PoE module

Ethernet Pro

Ethernet Shield for Arduino - W5200

Arduino Ethernet Rev3 Without PoE Module

Ethernet Shield W5100 For Arduino

in DFRobot Online Shop.


texts: MYO arm band based 6 degree of freedom robotic arm controlling?

texts: their is an arm band known as myo which can controll the gestures of hands and can transmitt it via its built in software or blutooth 4.0. i want to controll a robotic arm through it. so can any body help me with the programming and how to start.


texts: Is it possible my ATMega is burnt due to bad wiring?

texts:
While working on a project I tried sending data from my Arduino NANO to ATMega64 placed on AREXX Robot arm PCB via TXD/RXD. After plugging in VCC, GND, TXD and RXD to UART socket it didn't work so I figured the socket itself must be backwords or mirror image from my perspective. Then I tried plugging everything in on the other side of the socket and as I plugged VCC to one of the pins a little smoke came out (I can't specify exact place where smoke came from) and from now on there is no connection to the robot. However LEDs seem to work just like before the 'incident'. It can be seen as COM but, desktop app constantly displays 'Connection failed' when trying to access the robot. It seems that I plugged VCC to the MRESET pin and GND to the RXD1 pin of the ATMega64. Can anyone help define if my processor is burnt? And if so, what can I do to fix the robot? Are there any other ways to send data to ATMega considering it is already programmed adn I want to keep it that way? Unfotunately, replacing ATMega isn't possible for me. Thanks in advance for any help.
UART :

ATMega :

Robot PCB :


texts:
I'm trying to stack the Adafruit Data Logger Shield https://learn.adafruit.com/adafruit-data-logger-shield/overview onto a CuteDigi Sim900 GPRS Shield so that I can upload data (collected eventually by a GPS breakout) to a server at certain intervals.

The problem is that I can't seem to get the two shields to play nicely together. I'm a beginner with the Arduino and electronics in general, so hopefully this is just a noob issue.

When I power on the GPRS Shield, the data logger stops outputting the Date/Time to the serial monitor. And when I turn the GPRS Shield off, the serial monitor continues again and shows the Date/Time from the data logger.

They don't share any pins that I'm aware of, and I've tried connecting a 7.4V li-po for external power with no success.

Any help is greatly appreciated!


texts: Please , explain about MAX30100 using for Arduino to read ADC in format (0-1023)

texts: can anyone help me..? I am using MAX30100 with arduino, and my expectation is i can to process the ADC as usual (0-1023), but I do not understand the signal processing. Has anyone used the MAX30100 here before? if so, how to process the ADC's wavelength?


texts: How to count and list number of all UDP clients to WiFi softAP or event if new available?

texts:
I have simple ESP32 app (server, soft access point):

WiFiUDP Udp;
....
void setup()
{
 WiFi.softAP(ssid, password, WiFi_chennel);
 Udp.begin(portServer);
}
....
void loop()
{
 ....
 for(byte i=0;i<clients_count;i++)
 {
    Udp.beginPacket(IPs[i], portClient);
    Udp.write(packetBuffer,packetBufferSize);
    Udp.endPacket();
 }
}

(Clients only recieves data with Udp.parsePacket() )

So I have to get current clients_count and better also list of IPs addresses. Probably it have to be some event immediately after new client available (without sending addition packet from client to server).
I don't understand if wifi_softap_get_station_num available on ESP32 and how to use it.

UPD:
I see the fact, The server know of new "clients" availability at least it time of "Udp.endPacket();" and this affects work of this simple program with clients_count constant to maximum number of clients: if available only 1-2 clients - they get data good. If too many clients: all clients will get some % of corrupted messages or server freeze at all.


texts: I need to construct 4 reactors for an experiment requiring mixing. We want to automate the mixing and at the same time reduce cost. can we connect multiple stepper motors with 5 or 6 wires on one shield version 2?


texts: Counting revolutions of a DC motor with a Photo Interrupter

texts:
I have a DC motor which is rated at 11 200 RPM.

I would like to count the actual RPM (it seems to be maybe 1500 RPM from what I can tell manually.)

I bought a Photo Interrupter, and have connected it to pin A0. When the beam of the Photo Interrupter is broken, the reading drops to zero.

All seems to work well when using a delay of 100, but as soon as I drop the delay to less than about 50, I get multiple reads.

This is my code:

int must_print = 1;
int sensorValue = 0;

//the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  sensorValue = analogRead(A0);

  if (sensorValue > 0)
    {
      if (must_print == 1)
      {
        must_print = 2;
        Serial.println(sensorValue);
      }
    }

  if (sensorValue == 0) {
    must_print = 1;
  }

  delay(100);        // delay in between reads for stability
}

At delay(100) the Serial Monitor looks like this for a single interrupt of 10 seconds:

354

At delay(50) the Serial Monitor looks like this for a single interrupt of 10 seconds:

298
312
328
336
349
360
366
371

Thanks!


texts: Receiving and transmitting messages simultaneously

texts:
tldr; I am writing a mesh network software using arduinos. I need to wirelessly receive, process, and transmit data, all simultaneously. I am aware of protothreads library, and the other software solutions, such as using interrupts, however, I am using relatively high baud rates. Thus each nanosecond is of the essence. Does anyone have any other ideas for me to achieve this? my initial thought is to have 2 Arduinos functioning as a single node in the mesh. One will receive while the other transmits.

I am currently using these antennas to receive and send messages. I want to create a mesh network of Arduinos using these modules. I found several mesh libraries for Arduino, but none seem to quite do the task I need. So here is my plan which I will work through using an example. (This is a very naive explanation, and has flaws in it's implementation. This is just to give off the general idea).

Each Arduino will be connected to a receiver and a transmitter. Let's say I have just 4 nodes in the mesh.

Node #1 -> Address = 0xA031
Node #2 -> Address = 0xB042
Node #3 -> Address = 0xC053
Node #4 -> Address = 0xD064

I send a message to node A through USB. Let's say the message is "SOS!"
Node A will reconstruct the message in the following way so that the new message is "0xA031_SOS!"

Now, Node A will begin transmitting this message continually. Let's say only Node C picks up the message. Node C will pick up the message and perform the following checks. (I will have 2 queues. A receiving queue and a transmitting queue. So as soon as a node receives a message, it will be placed in the receiving queue. And then it will run the following checks before sending it to the transmitting queue.)

Is the address a recognized/valid address? Handle appropriately
Is the address of the received message the same as the node's own address?

If address is same, check if the message received is the same message being transmitted currently by itself. If so, discard the message and tell transmitter to stop transmitting that message(This means that the message was originally transmitted to another node and came back, which means, it doesn't need to be re-transmitted any more). If the address is not the same, then send the message to the transmission queue.

Now the transmission will be handled the following way.

Check if there is anything in the transmission queue. If there is, transmit this message continually until told not to.
If the transmitter is told to not transmit that message any longer, that message will be popped of the queue.

So what happens? Node A continually sends a message. Node C receives the message and re-transmits. Because Node C was able to pick up Node A's message, it is in range and Node A will pick up Node C's message. Now, Node A will check the address, and say "oh, this is the same address as me." Then it will check if the message being transmitted is the same as what was received. If so, then it will tell the transmission queue to no longer transmit that message. (This almost like a form of back propagation).

Now I realize there are a million ways to have collisions and infinite loops. I will be eventually writing a software to resolve these things. But I hope I am giving off the general idea of how the network will work.

My questions:

As is clear from my explanation, because I am receiving and transmitting simultaneously, is there a way for me to do multi-threading? I am aware of protothreads and the other things mentioned in this post. However, all of them only offer a software solution, and not a hardware solution. So does anyone have any ideas of how I'd work around this? My initial thought is to have each node be composed of 2 Arduinos. Any one have any other ideas?
Also, does anyone have a better idea of implementing the mesh to do what I want it to?

I know this is a very convoluted, hefty post. Please let me know what I should clarify. Thank you.


texts: Global memory reduction when using SPI/SD

texts:
I want to use an SD card and when including the library both SPI.h and SD.h are included. Also later I want to use an external SRAM chip (probably using SPI.h as well). However, without the SRAM chip my sketch uses around 849 bytes of global memory, where I expect most of it taken by the SD.h / SPI.h combination. Without these includes only 9 bytes are used.

How can I reduce the amount of global memory (still I want to use the SD and SPI interface)?

Edit:

According to a remark below 512 bytes are used for the SD so that explains mostly of the 849 bytes. And some additional questions:

Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes ...I only need to read a file (128 KB) and copy it to an SRAM (external). And I don't mind if it will be transferred in 16 byte blocks. Actually, I could get rid of the buffer at all after the SD to SRAM copy.

My ultimate goal is to leave 1KB + some dynamic memory (for function call stacks/local variables). However, finally I need to move to the Arduina Mega anyway, but was hoping I could already start the project with my Arduino Uno.


texts:
How do I split a string into two based on it's length to display on a 2x16 LCD?

I have seen a function called length() to get the length of a string. But, any ideas how to split it in to 2x16 and trim the rest of the string?

Thanks


texts:
I have a ESP8266 and I wonder if it is possible to create a Wi-Fi signal repeater using this module.

I can create a network so that devices connect it.
I can connect to an existing network.

But I can not connect the network created with the network that I connected

Does anyone know how to do this? or you have any examples?


texts: I've been doing some XBee experiments with Arduino Pro Mini 5V. I knew that XBee S2 is 3.3V only, so I've connected its Vcc to 3.3V from external supply, but I had also connected XBee RXTX to arduino TXRX, in this order, and since that i can't use my XBee Explorer to communicate with XCTU on my notebook. The connections with an 5V Arduino RXTX can cause damages to the XBee, even if the XBee was powered with 3.3V?


texts:
I have Code for Mod bus Library as below. I have Gone through lots of forum. How to assign device ID, slave address, length using below library function:

#include <SimpleModbusSlave.h>
#define  LED 9
enum
{

  ADC_VAL,
  PWM_VAL,
  HOLDING_REGS_SIZE // leave this one
};

unsigned int holdingRegs[HOLDING_REGS_SIZE];
void setup()
{
  modbus_configure(&Serial, 9600, SERIAL_8N2, 1, 2, HOLDING_REGS_SIZE, holdingRegs);
  pinMode(LED, OUTPUT);
}

void loop()
{
  modbus_update();
  holdingRegs[ADC_VAL] = analogRead(A0); // update data to be read by the master to adjust the PWM
  analogWrite(LED, holdingRegs[PWM_VAL]>>2); // constrain adc value from the arduino master to 255
}

I am getting Error has.

SimpleModbusSlaveArduino.cpp: In function 'void setup()':
SimpleModbusSlaveArduino:79: error: 'SERIAL_8N2' was not declared in this scope

I have  made changes in the lib as in forum. but I found no value read by my software.

Master sending below request on read mode. But not receiving anything.

12:31:02.953: Com8, Baud Rate: 9600, Data Bits: 8 Bits, Parity: None, Stop Bits: 1 Stop Bit
12:31:02.953: Echoback: On, RTS Control: On, Transmit Delay: 5 ms, Response Delay: 1000 ms
12:31:02.953: Read Holding Register(s), Repeat Loop
12:31:02.953: Device Address: 01h, Register: 0000h
12:31:02.953: |-> Read Register: 0000h
12:31:02.968: -> [01h] [0Dh] [00h] [00h] [00h] [01h] [CBh] [EDh]

CHANGES MADE IN AS IN FORUM MENTIONED


texts: Arduino Program for Olimex ekg/emg shield to detect heart rate in bpm as well as show ECG in ElecGuru software

texts:
The manual of olimex ekg/emg shield provides a link for ShieldEkgEmgDemo code, it can show ecg in realtime in a software ElecGuru. The link to software is also provided in the manual. I need to get the numerical value of heart rate in bpm as well as the ecg. I want to implement this in a larger program where I can use something like this.

if(heartRate > 90){
        //do something
}

I have an Arduino UNO board and an Olimex ekg/emg shield with electrodes. I tested the shield with demo code and it worked fine. I got a clean ECG on ElecGuru.


texts: Powering SD breakout board with 3.7V battery

texts:
So in a previous post I asked if I could charge an SD card breakout board with a 3.7V LiPo battery, and I got a positive response, so I did it.

The problem is that it seems not to be enough, since, with the exact same wiring, if I supply it with my Arduino Uno, it works perfectly, but when I change the supply to the battery it gives an error. The following text is the result of an Arduino example script:

When connected with the Arduino:

Initializing SD card...Wiring is correct and a card is present.

Card type: SDHC

Volume type is FAT32

Volume size (bytes): 2696937472
Volume size (Kbytes): 2633728
Volume size (Mbytes): 2572

Files found on the card (name, date and size in bytes):
SYSTEM~1/     2017-04-27 15:20:04
  WPSETT~1.DAT  2017-04-27 15:20:04 12
  INDEXE~1      2017-04-27 15:20:14 76
TEST0.TXT     2000-01-01 01:00:00 49050
TEST1.TXT     2000-01-01 01:00:00 60231
TEST2.TXT     2000-01-01 01:00:00 1044
TEST3.TXT     2000-01-01 01:00:00 34831
TEST4.TXT     2000-01-01 01:00:00 189736
TEST5.TXT     2000-01-01 01:00:00 12419

When connected to the battery:

Initializing SD card...initialization failed. Things to check:
* is a card inserted?
* is your wiring correct?
* did you change the chipSelect pin to match your shield or module?

or

Initializing SD card...Wiring is correct and a card is present.

Card type: SD1
Could not find FAT16/FAT32 partition.
Make sure you've formatted the card

I've tried to supply the breakout board both through the 3V and 5V input. Can anyone notice what am I doing wrong?


texts:
I am moving my Arduino project to another platform, operating at 3.3V. (5V from USB not useable due to some 3.3V-only chips in the design) Having read about this it seems that 12MHz is a good speed to use, and my stock USB to UART converter, CH340G does call for a 12MHz crystal.

Now what is the best way to share this 12MHz clock between CH340 and ATmega328P, eliminating an extra crystal? Can I tap off XO pin from CH340 with crystal attached, and carry it to the XTAL1 pin of the ATmega?

EDIT

If sharing clock requires some fine tuning, what about building a reference clock out of 74LVC1G04 and 74LVC1G06 chips and clock both chips from this?


texts:
I have tried everything on this url
https://stackoverflow.com/questions/10165761/java-cant-connect-to-x11-window-server-using-localhost10-0-as-the-value-of-t
session output:
root@whale:/home/kermit# echo $DISPLAY
localhost:1.0
root@whale:/home/kermit# cd dev/sht30/
root@whale:/home/kermit/dev/sht30# arduino --upload sht30v1.ino --port /dev/ttyUSB0
Exception in thread "main" java.awt.AWTError: Can't connect to X11 window server using 'localhost:1.0' as the value of the DISPLAY variable.
        at java.desktop/sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
        at java.desktop/sun.awt.X11GraphicsEnvironment$1.run(X11GraphicsEnvironment.java:102)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.desktop/sun.awt.X11GraphicsEnvironment.<clinit>(X11GraphicsEnvironment.java:61)
        at java.base/java.lang.Class.forName0(Native Method)
        at java.base/java.lang.Class.forName(Class.java:315)
        at java.desktop/java.awt.GraphicsEnvironment$LocalGE.createGE(GraphicsEnvironment.java:101)
        at java.desktop/java.awt.GraphicsEnvironment$LocalGE.<clinit>(GraphicsEnvironment.java:83)
        at java.desktop/java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:129)
        at java.desktop/sun.awt.X11.XToolkit.<clinit>(XToolkit.java:231)
        at java.base/java.lang.Class.forName0(Native Method)
        at java.base/java.lang.Class.forName(Class.java:315)
        at java.desktop/java.awt.Toolkit$2.run(Toolkit.java:588)
        at java.desktop/java.awt.Toolkit$2.run(Toolkit.java:583)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.desktop/java.awt.Toolkit.getDefaultToolkit(Toolkit.java:582)
        at processing.core.PApplet.<clinit>(Unknown Source)
        at processing.app.Preferences.save(Preferences.java:735)
        at processing.app.Preferences.init(Preferences.java:249)
        at processing.app.Base.main(Base.java:117)

How do you run arduino in headless mode on a raspberry pi?


texts: What happens if I try to draw power from the VIN port while under USB power on an Uno?

texts: I would like to have a shield permanently attached that use the VIN (not 5v) for it's power - the problem comes in when I want to program the arduino (via the USB port), do I need to also have the barrel connector plugged in, or can I just expect the shield to not work (no, it won't be damaged from not getting enough/any power), but have the arduino itself be fine - or am I somehow damaging the power regulator by attempting to use it in reverse?


texts:
Does somebody know which is the maximum serial speed one can achieve by using the Microchip SAM3X8E microprocessor with Serial Communication between other uC with a RS485 module?

The Arduino Due seems to be limited up to 115kbps, the USB (UOTGHS) should reach 1.5Mbps (low speed) without trouble, but I am not sure about the UART

From Microchip SAM3X8E Datasheet section 34.5.1 Baud Rate Generator, the UART baud rate should be the Master Clock MCK divided by 16, the maximum value given by setting the clock divisor UART_BRGR to 1, the minimum value after 0 (UART disabled).

Hence the Master Clock MCK should be around 84MHz (its Maximum Possible Clock?), and then the Maximum Baud Rate should be 5.25Mbps?

Is this right?

Thanks in advance


texts: Using Multiple identical sensors - Beginner

texts:
I'm trying to make an interactive installation where I have 6 pressure pads that each control an Air Fan. The pressure sensors ideally will be on chairs.

I would like the changes in pressure to change the speed of the Air Fans.

What is the easiest way for me to do this? Can I do it with just an Arduino?

I haven't bought anything yet as I'm assessing what the best route is.


texts: Arduino controlled relay for certain duration of time

texts:
I am using a relay on my Arduino Uno and i want it to be on LOW for a calculated interval of time, let's say ftime=7 seconds, and after that i need it to be set as HIGH (no power through relay). My code below makes no changes to the relay state. How would that be possible? I tried to use "delay()" too (which i know that is generally a bad idea), but had no success.

 unsigned int interval = ftime*1000; //ftime in ms
do
  {
  digitalWrite(Relay1, LOW);
  }
  while(timeElapsed < interval);
digitalWrite(Relay1, HIGH);

Also, if i try without:

digitalWrite(Relay1, HIGH);

relay is LOW (motor running) but it never returns to HIGH obviously.


texts:
I've connected a real time clock ZS-042 to my Arduino Uno. I tried to set the time, using an example from DS1307RTC library. Here is my code:

#include <DS1307RTC.h>
#include <Time.h>
#include <Wire.h>

*const* char *monthName[12] = {
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

  tmElements_t tm;//it says that problem is in here

void setup() {

  bool parse=false;
  bool config=false;

  // get the date and time the compiler was run
  if (getDate(__DATE__) && getTime(__TIME__)) {
    parse = true;
    // and configure the RTC with this info
    if (RTC.write(tm)) {
      config = true;
    }
  }

  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor
  delay(200);
  if (parse && config) {
    Serial.print("DS1307 configured Time=");
    Serial.print(__TIME__);
    Serial.print(", Date=");
    Serial.println(__DATE__);
  } else if (parse) {
    Serial.println("DS1307 Communication Error :-{");
    Serial.println("Please check your circuitry");
  } else {
    Serial.print("Could not parse info from the compiler, Time=\"");
    Serial.print(__TIME__);
    Serial.print("\", Date=\"");
    Serial.print(__DATE__);
    Serial.println("\"");
  }
}

void loop() {
}

bool getTime(const char *str)
{
  int Hour, Min, Sec;

  if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
  tm.Hour = Hour;
  tm.Minute = Min;
  tm.Second = Sec;
  return true;
}

bool getDate(const char *str)
{
  char Month[12];
  int Day, Year;
  uint8_t monthIndex;

  if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
  for (monthIndex = 0; monthIndex < 12; monthIndex++) {
    if (strcmp(Month, monthName[monthIndex]) == 0) break;
  }
  if (monthIndex >= 12) return false;
  tm.Day = Day;
  tm.Month = monthIndex + 1;
  tm.Year = CalendarYrToTm(Year);
  return true;
}

and this is my output:

Arduino: 1.6.12 (Windows 10), Плата:"Arduino/Genuino Uno"

In file included from C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino:1:0:

C:\Users\папа\Documents\Arduino\libraries\DS1307RTC/DS1307RTC.h:19:22: error: 'tmElements_t' has not been declared

     static bool read(tmElements_t &tm);

                      ^

C:\Users\папа\Documents\Arduino\libraries\DS1307RTC/DS1307RTC.h:20:23: error: 'tmElements_t' has not been declared

     static bool write(tmElements_t &tm);

                       ^

SetTime:10: error: 'tmElements_t' does not name a type

   tmElements_t tm;

   ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'void setup()':

SetTime:21: error: expected primary-expression before ')' token

     if (RTC.write(tm)) {

                     ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'bool getTime(const char*)':

SetTime:54: error: expected unqualified-id before '.' token

   tm.Hour = Hour;

     ^

SetTime:55: error: expected unqualified-id before '.' token

   tm.Minute = Min;

     ^

SetTime:56: error: expected unqualified-id before '.' token

   tm.Second = Sec;

     ^

C:\Users\6939~1\AppData\Local\Temp\arduino_modified_sketch_566010\SetTime.ino: In function 'bool getDate(const char*)':

SetTime:71: error: expected unqualified-id before '.' token

   tm.Day = Day;

     ^

SetTime:72: error: expected unqualified-id before '.' token

   tm.Month = monthIndex + 1;

     ^

SetTime:73: error: expected unqualified-id before '.' token

   tm.Year = CalendarYrToTm(Year);

     ^

exit status 1
'tmElements_t' does not name a type


texts: How do I implement a userspace bootloader on Arduino Due?

texts:
Is it possible to use a custom bootloader, that loads and executes a main program stored for example on an SD card? The idea is to make it possible to update the Arduino remotely.

I tried this with a bootloader, which writes the program into the flash storage with a 32KB offset and then uses a function pointer with that address (0x88000) to continue execution there. The 0x80000 is as far as I am informed the address offset of the flash storage. It can be written on Due boards with this library: https://github.com/sebnil/DueFlashStorage. The problem was that this just hasn't worked, the Arduino simply stopped responding after the function pointer being executed. I would appreciate any information or hints on this topic.


texts:
I am testing a WinCE device that loses all USB communication infrequently. I need to detect when the USB fails on this device. When it fails, the power is intact at the port, just no data at all on D+ and D- (I verified this with an oscilloscope). This host device is basically a black box to me so I can't do anything to it but check it's state.

My proposed solution:  Use an arduino of some type (preferably an UNO since I have one already) programmed to detect USB activity to let me know when USB is failing on the host device I am testing.

Is this possible? The arduino seems like a good solution for me because I assume it is a USB client, which I need in this scenario.  Any example or pointing me in the right direction would be of great help.  Thanks!


texts:
I have this cheap RF link that I had working with the Arduni UNO, but I wanted to make it smaller and ATTiny85 should do the trick. The RF module is connected (data pin) to PB3 on the ATTiny.

But I am having some problems. It does not work, and I don't know why. My code:

#include <SoftwareSerial.h>

// PINS
#define SERIAL_TX PB3

SoftwareSerial mySerial(-1, SERIAL_TX);

void setup() {
  pinMode(SERIAL_TX, OUTPUT);
  mySerial.begin( 1200 );
}

void loop() {

  mySerial.write(0xAA);
  mySerial.write(0xAA);
  mySerial.write(0xAA);

  delay(1000);
}


texts: Connecting via serial with Arduino comand line

texts:
Since inotool is dead, I'm trying to transition over to Arduino's built-in command line tool.

It seems largely equivalent, but the one feature it seems to be missing is a serial interface. e.g. Running ino serial would open a simple serial interface to the Arduino, providing invaluable debugging info from any Serial.print() statements.

How is this accomplished with the current Arduino command line tool?


texts:
I want to create a small single threaded os for my arduino.The first thing I want to do is to allow my arduino to read a section from flash/eeprom and execute it. I have some question regarding the memory. The microcontroller is executing one command at a time from..where? Does it directly acces the flash containing the code and take every command at a time?(that would be slow) Or does it first load the entire program into sram?(also wouldn't make sense because sram is 2k while flash is 32k). Either way,if I can find in sram /flash my code( or the header to some void) then i could jump there.Am i wrong?Is it possible(to do such os)?

Something like this:

uint16_t addr=0x1234;
void (*function)(void)=addr;
function();

(or maybe with some avr like assembly code?)


texts: Converting string to byte array and byte array to string?

texts:
I am trying to create a string message and then encrypt it via AES but the example only accepts byte array as input. How can I convert fullmessage string to message byte array to encrypt it? Checked similar questions but couldn't resolve the problem.

void loop ()
{
  dt = clock.getDateTime();
  String dash = "-";
  String comma = ",";
  String time = dt.year + dash + dt.month + dash + dt.day + dash + dt.hour + dash + dt.minute + dash + dt.second;
  String status = "OK";
  String fullmessage = time + comma + status;
  byte message[]= "anything";
  plainLength = sizeof(message)-1;
  padedLength = plainLength + N_BLOCK - plainLength % N_BLOCK;
  prekey(256,message);
  delay(2000);
}


texts: Sending multiple data with SPI interface monitored by an Osciloscope

texts:
I have multiple 32-bit data stored in an array, and I want to sequentially send them by SPI interface. I want to check that my code is correctly sending data by SPI interface, so I upload the code and connect my Linkit7697 to an oscilloscope.
The expecting waveform is like this:

But it turns out to be like this:

It seems that all data are composited together in every 32 bits.
What's wrong? Any idea?
Here is my code:
#include <SPI.h>

#define SPI_MOSI (11)
#define SPI_MISO (12)
#define SPI_CS (10)
#define SPI_CLK (13)

uint32_t test[]={
  0xF0000000,   //11110000000000000000000000000000
  0x00F00000,   //00000000111100000000000000000000
  0x0000F000,   //00000000000000001111000000000000
  0x0000000F    //00000000000000000000000000001111
  };

int i = 0;

void setup() {
  digitalWrite(SPI_CS,HIGH); //Set slave select to high, linkit7697 is Master
  SPI.begin();
  SPI.beginTransaction(SPISettings(20000000,MSBFIRST,SPI_MODE0 ));

}

void loop() {

  for (i = 0; i < 4; i++){
    digitalWrite(SPI_CS,LOW);
    SPI.transfer(&test[i],4);
    digitalWrite(SPI_CS, HIGH);

  }

}


texts:
I am trying to build a WiFi humidity and temperature sensor. My board is a nodeMCU using the ESP8266 connected via USB. The board is working fine with various WiFi examples and various serial examples. Hence I guest my environment is OK.

Now I am trying to connect a DHT22 to read temperature and humidity. To reduce the error sources I boiled down my code to the standard DHT example:

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);

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

void loop() {
  delay(2000);

  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.println(" *C ");
}

Nevertheless I always get the message "Failed to read from DHT sensor!".

Regarding the hardware I tried connecting the sensor with or without the 10k resistor, tried different DHTs and different pins. To rule out the DHTs I connected them with an Arduino Nano where these are working fine (both with and without resistor and using the same code). The only difference I see is that the Arduino is using 5V while the ESP8266 is using 3.3V - which is nonetheless inside the rating of the DHT.

Any ideas?


texts: Why does reading an analog pin give a different results when interfacing with Processing?

texts:
I am interested in measuring the voltage over an analog pin (A6). When I use the Arduino IDE to print the results through the serial I get values around 300.

Here's the code

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

void loop(){
   Serial.println(analogRead(A6));
   delay(50);
}

When I try to run a equivalent program using Processing and interfacing it through Firmata and the corresponding library, I get values around 900.

Here's the Processing code:

import cc.arduino.*;
import processing.serial.*;

Arduino arduino;

void setup(){
   arduino = new Arduino(this,Arduino.list()[0], 57600);
   delay(2000);
}

void draw(){
  System.out.println(arduino.analogRead(6));
  delay(50);
}

Does anybody know what could be the issue? I should probably rather trust the values given directly by the Arduino without interfacing, right?

The pin is connected to a circuit with supply voltage.
I also tried reading the values directly using Serial in Processing (so without using the cc.arduino.* - library) and that showed me the values around 300. So I guess the difference is caused by the arduino.analogRead() method. I am puzzled as to whether that's a bug in the library or something else.

The problem seems to be me not properly initialising the pins. But calling

arduino.pinMode(6,Arduino.ANALOG);

in the setup method does nothing, as does Arduino.PWM, SERVO and any combination I tried. I thought, maybe Processing tried to assign D6 as analog instead of A6, but changing the value to 20 (as it's the pin number according to this) simply caused an OutOfBoundsException.


texts: Why does my code or Serial Monitor hang with analogRead?

texts:
I have the following code in loop() to collect values from an electret microphone

for(int i=0; i<sampleSize; i++){
  analogVal[i]= analogRead(ADC_Pin);
  sumOfSquares= sumOfSquares+sq(analogVal[i]);
}
Serial.print("Sum of squares: ");
Serial.print(sumOfSquares);

where sampleSize is an int variable, I've tried numbers from 3 to 1000, which is my desired value. ADC_Pin is an int variable set to be A1 and has been properly initialized through pinMode. analogVal is an int array of size sampleSize.

My circuit appears to be fine because the output produces a reasonable amount of voltage. I've tried eliminating the line with sumOfSquares and just having the first line in the for loop. However, the Serial Monitor hangs and does not display any values. The serial communication is at 9600 bps.


texts:
I would like to use the JSN-SR04T 2.0 in order to find the depth of a body of water. Once I test the sensor in a body of water, the distance measurements are then constant at about 20 cm. I then changed my distance formula to account for the speed of sound in water, but the measurements are still constant despite change in the body of water. Does anyone have any recommendations on how to obtain better measurements underwater?

#define trigPin 2
#define echoPin 3

// Define variables:
long duration;
int distance;

void setup() {
  // Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // Begin Serial communication at a baudrate of 9600:
  Serial.begin(9600);
}
void loop() {
  // Clear the trigPin by setting it LOW:
  digitalWrite(trigPin, LOW);

  delayMicroseconds(5);
 // Trigger the sensor by setting the trigPin high for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);

  // Calculate the distance:
  distance = duration*0.034/2;

  // Print the distance on the Serial Monitor (Ctrl+Shift+M):
  Serial.print("Distance = ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(100);
}


texts: Arduino UNO WiFi "wifi shield not present"

texts:
I currently use the Arduino UNO WiFi, but when I try to use the WifiChatServer example, I keep getting the same error: wifi shield not present.

What am I doing wrong?


texts: Feeble click in relay but it doesn't get activated when connected to Arduino circuit

texts:
I have an Arduino uno board and I have a soil moisture sensor

connected the digital output pin of the sensor to Arduino input pin
connected an output pin of Arduino to the INPUT pin of the relay board
programmed the Arduino such that if input is HIGH then the OUTPUT should be HIGH as well
connected 5 v pin of Arduino to vcc of the relay board
connected gnd pin of Arduino to gnd of the relay board

When my sensor outputs a HIGH DO (digital output), the relay only creates a feeble click sound and does not get activated. The Relay board LED does light up but the relay itself does not work (NC remains closed and NO remains open).

Do I need to supply an external VCC to the relay board? If yes then how should I set up the circuit?

A picture of the relay board is attached. You are right ... it is a 12 v relay. Do I need a 12 v external power source with IN1 coming from Arduino? Any help will be much appreciated.


texts: ESP12F works indefinitely, then gets stuck in unrecoverable hardware WDT "boot loop"?

texts:
I have a sketch running on a number of ESP12F modules (AiThinker). They can work for months on end, can be power cycled, can be moved around, etc. It is a complex sketch with multiple parts and is still using the 2.4.2 core.
What I've seen happen on an increasing number of these is that the modules can get stuck in some kind of boot loop, that I am suspecting is the hardware watchdog kicking in.
On resetting a faulty device the following is printed to the debug port at 74880:
ets Jan  8 2013,rst cause:2, boot mode:(3,7)

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

I think this equates to:

External pin reset or wake up from deep sleep
Booting from flash
SDIO High Speed V2 IO / UART1 (I have no been able to find any explaination to what this actually means, and many posts reccomend essentially ignoring!)

About 1.5 seconds later, the following is printed at 74880:
ets Jan  8 2013,rst cause:2, boot mode:(3,6)

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

The only difference here I think is that (3, 7) has changed to (3,6) which equatest to:

SDIO Low Speed V1 IO / UART1 (again, no idea what this means)

After this, every 5.5 seconds (roughly) the following is printed, this time at 115200:
ets Jan  8 2013,rst cause:2, boot mode:(3,6)

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

This is the same ouput as before, just output at a different baud rate.
This boot loop will continue indefinitely (I left one in this state for days to see if anything happened). Power cycling it just takes it back to the first debug messages, then just sits back in the boot loop.
No serial output from my actual sketch is ever seen. This, along with the 5.5ish second loop leads me to think that the hardware watchdog is triggering and not even allowing my sketch to run. Does that sound right?
This currently seems to be affecting around 5 out of 50 devices. Most are happily running along without a care. The affected devices can be reflashed, seemingly successfully, and will run as they should, but after about 5-10 power cycles they fall back into this loop. It's like the hardware has been permanently damaged and can never be relied on again!
Has anyone seen this behaviour before? What are people's opinions on what might have caused this? Can bad code permanently corrupt the hardware in the way I think I am seeing?


texts:
Im doing a project in which there are two arduinos with both of them having hc05 bluetooth modules.
Now how to connect them both so that both stay connected and one is used as a remote control so that when i press a push button on remote arduino it will send data via bluetooth to the reciever arduino which in turn will do whatever task is defined.
Can any one help me with this process.I know how to write the code but i do not know how to connect two bluetooth modules and use them in separate arduinos.


texts: How to transmit string data using the rc-switch library?

texts:
I am using the rc-switch library for sending and receiving data. In rcswitch library, there is no method to send string data. I am using below method to send the string message in char buffer.

send_string("Hello World!");
---------------------------

void send_string(const char *str)
{
int i = 0;

for (char *p = str; *p; p++ ) {
mySwitch.send((i<<8) + *p, 16);
i++;
}
mySwitch.send((i<<8) + 255, 16);
}

And I am receiving is using this Serial.print((char)mySwitch.getReceivedValue()); build in method. But I am getting this message.

H
H
H
e
e
e
l
l
l
l
l
l
o
o
o

W
W
W
o
o
o
l
l
l
d
d
d
!
!
!

Now how can I get my original message?


texts: "Does not name a type" error with Serial.print

texts:
I am getting an error that I have never seen before and don't know how to fix. Basically I am trying to print a string (stored in thermistor) to the serial monitor. When I run the code I get an error message that says: exit status 1
'Serial' does not name a type.

What can I do fix this error?

void setup() {
Serial.begin(9600);
pinMode(4, OUTPUT);
pinMode(6, OUTPUT);
pinMode(8, OUTPUT);

}

void loop() {

} <==== ERROR: loop() ENDS TOO EARLY
String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
String lilyPad = codeWrite(6, HIGH, LOW, LOW);
String thermistor = codeWrite(8, HIGH, HIGH, LOW);
Serial.println(thermistor);
delay(1000);

String codeWrite(int pin, char output1, char output2, char output3)
{
  digitalWrite(pin, output1);
  int A = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output2);
  int B = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output3);
  int C = digitalRead(pin);
  delay(11);
  String code = String(A) + String(B) + String(C);
  <==== ERROR: MISSING RETURN STATEMENT
}


texts: How can I create multiple running threads?

texts:
Is there a way I can have multiple parts of the program running together without doing multiple things in the same code block?

One thread waiting for an external device while also blinking a LED in another thread.


texts: Struggling to understand how Bluetooth serial is related to USB on Arduino

texts:
I've recently acquired a Bluetooth module to attach to my Arduino Uno, but I'm trying to draw parallels to the standard method of communication that I'm familiar with, which seems to be just directly reading or writing to sensors through methods like digitalRead and digitalWrite, respectively. Additionally however, it seems like it's also possible to connect to a serial console, through the Serial class. These make sense, and I've used both individually (serial console viewed by the built-in Serial window in Arduino IDE, and serial write done through Serial.print/println()).
However, in the Bluetooth module I purchased (HW-10), there are pinouts that connect to the TX/RX ports, which I've currently left unconnected since I'm not using the Bluetooth module or any other serial module. My question is, once I connect these, does this completely replace the connection through USB that is currently used to interface with the Uno?
If so, I had a set of specific functionalities in mind for whether these would be "replaced" by connecting the module through the 4 pinouts (TX, RX, VCC, GND):
1. Serial: Can I write and access the serial monitor through the IDE by connecting to 9600 baud, both in code and in the Serial Monitor
2. Pins: Do these connections also allow me to write and read signals from all of the pins, including analog and digital
3. Sending code: Can I still send code through Bluetooth without needing a USB connection?
Apologies if this question seems really obvious or specific, I'm confused as I've read a bunch of wording saying that the Bluetooth module uses a "serial connection", when I only understood serial functionality as being a method of outputting text, not controlling the Arduino. Thanks in advance for help!


texts: Waking an ESP8266 from Light-Sleep using a signal from MQTT?

texts: I was wondering if it would be possible to wake an ESP8266 from a request over MQTT while it is in Light-Sleep mode? I am planning to implement a smart switch that would receive messages from a Raspberry Pi to turn off and on, however, I don't want to have to manually hit a button to trigger an external reset (I've seen this done in many examples already). I also don't think it would be efficient for me to just set a timer and have the ESP wake up in intervals. For instance, if I want to have the smart switch turn on an appliance and the PI sends a request over MQTT when the ESP is sleeping... this will do me no good. Curious if anyone has run into this issue before and what recommendations you have.


texts: unable to install usbserial driver for GPRS shield with mac air vs. 10.9

texts:
Despite all my efforts and web crawling I can not install the necessary driver to connect my Arduino uno R3 to the GPRS shield from seeedstudio. I have attempted downloading the VCP driver from http://www.ftdichip.com/Drivers/VCP.htm
I have tried the solution offered here https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/mac for Yosemite and beyond through the AppleUSBFTDI driver as well as the solution offered by FTDI's script. Any help will be greatly appreciated. Please let me know if I can provide any more information.


texts:
I realized I don't fully understand how Arduino code handles variable lifetime. My tendency is to keep variables in the narrowest scope (which I realize isn't as important in Arduino code, but, habits...). But how inefficient is this?

Given these possible variations:

 const int c1 = 2, c2 = 7, c3 = 9;

 void functy();

 int foo[3] = {c1 | c2, c3, c2 | c3};

 static int foo[3] = {c1 | c2, c3, c2 | c3};

 const int foo[3] = {c1 | c2, c3, c2 | c3};

  ....

In case 1, foo is both allocated and initialized each call.

In case 2, foo is allocated only once, but is it initialized on each call?

In case 3 I assume that allocation and initialization are done only once? Is that true?


texts: Will the Uno bootloader work in the Duemilanove?

texts:
I had an old duemilanove lying around (Which was not working because i accidentially busted the atmega) and I recently bought some atmegas pre-flashed with the UNO bootloader. So I tried to put one of those in it, and it seems to work fine except that I have to select the UNO board in the arduino IDE.

My question is: Is there anything problematic to be aware of when using the UNO bootloader in an duemilanove?


texts: ESP8266 stops working when I use 2x static const char(PROGMEM)

texts:
*Sdk version: 2.2.2-dev(5ab15d1)
*Core Version: 2_6_1

This is the error returned:

Exception 3: LoadStoreError: Processor internal physical address or data error during load or store PC: 0x4000bf64 EXCVADDR: 0x4024e963
Decoding stack results
0x4020175d: HTML1(String) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266/WString.h line 128
0x40238c26: umm_info(void*, int) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\umm_malloc/umm_info.c line 164
0x40100278: millis() at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\core_esp8266_wiring.cpp line 188
0x40238c26: umm_info(void*, int) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\umm_malloc/umm_info.c line 164
0x4020af74: String::copy(char const*, unsigned int) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\WString.cpp line 214
0x40201a3c:

Code:

static const char HTML1[] PROGMEM = R"=====(
<!DOCTYPE HTML><html><head>
<meta charset='utf-8' name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0'>
)=====";

static const char HTML2[] PROGMEM = R"=====(
<button type='button' onclick='sendData(2)'>Test2</button>
)=====";

String html_return = HTML1;
html_return += "<button type='button' onclick='sendData(1)'>Test</button>";
Serial.println("Before Second Const Char");
html_return += HTML2; //<< ESP stops working here


texts:
I am currently trying to connect my Arduino Uno to my computer and let them communicate via UART. I started using a project from Github (here), which I'm trying to modify to get the next step via UART. Because of that, I'm not able to switch programming languages and also need to override the bootloader.

However, I can't get the serial connection to work.

#include "Joystick.h"
#include <avr/io.h>
#include <util/delay.h>
#include <Arduino.h>

These are the #include statements at the top, but <Arduino.h> can't be found...

If I remove these statements, Serial can't be found (from the main-Method: Serial.begin(9600);)

It's my first time to program with C, did I overlook a stupid mistake? Thanks for any help...


texts:
I want to use an Arduino Genuino Zero as a Modbus slave. I tried to search on google, and found a library. When I try using the library, I get a timeout error.

Can anyone tell me how to solve that error? Did anyone manage to get the Arduino Modbus RTU slave library working?


texts: U8glib+ 7-pin SSD1306 gives moving text without explicitly specifying in code

texts:
This is my code.
#include <U8glib.h>
U8GLIB_SSD1306_128X64 u8g(12, 11, 8, 9, 10);
void clear_screen();
const int pageCount = 1;
int p;
void (*pages[pageCount])() = {clear_screen};
int duration [pageCount] = {2000};
void setup() {

  u8g.setFont(u8g_font_unifont);
  u8g.setColorIndex(1);
  p = 0;
  Serial.begin(9600);

}

void loop()
{
u8g.firstPage();
  do {
    (*pages[p])();
  } while( u8g.nextPage() );
  delay(duration[p]);
  p = p+1;
  if (p == pageCount)
    p=0;
}
void clear_screen()
{
  u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 20, "BP");
  }

This is the output is a floating text which says BP starts at 20 y length and progresses towards the right after every page refresh. and moves 20 y length down as soon as it reaches the end of the OLED
Check this video out.
Video to the Error


texts:
I am planning to build my own micro quadcopter, so I bought an Arduino 101 and 3.7v micro DC motor.

So the next step is finding a motor driver that can control these four motors, using PWM pins on the Arduino board. I spent a lot of time searching for it, but all I found was a 5v motor driver and other types of Arduino shields that can't work in my project. Has anyone my requirement (name of motor drive, micro-controller, circuit)?

Thanks in advance.


texts: What is importance of the reflow profile?

texts:
I was reading the MPU6050 datasheet to understand all the type of errors that affect the accelerometer, after finding information on the Reflow Profile i look up on wikipedia the Reflow Soldering Definition

As a noob i can't understand the importance, initially i though it was correlated with the temperature effect on the accelerometer bias, but i was wrong.

Why is important?

How do you read this values?(or when you use this data)


texts:
When I'm uploading a sketch I get the message:

  avrdude: ser_open(): can't open device "/dev/cu.usbmodem14201": No
  such file or directory.


texts:
Im working on a RGB LED matrix project (10 x 10 Neopixels) and I'm using classes to handle the different hardware components. Whats the best way to deal with multiple files in the project eg, I have a class which holds the various display functions such as writing text and drawing circles, but every time I change something it takes ages to compile (Greater than 30 seconds) is there a way to have multiple files without using classes?

Any help would be greatly appreciated.

Cheers


texts: ESP8266 Webserver ESP8266WebServer move Handler-Function in separate .h .c file

texts:
The plan is to create a bigger project and to split the ESP8266 webserver-code over several modules (.h .c files). The main problem is that the ESP8266WebServer server is not declared in the index.h and index.c files.

What I've been trying to do:

Content main.c

#include <ESP8266WiFi.h>
#include "ESP8266WebServer.h"
#include "index.h"

ESP8266WebServer server(80);
const char* ssid =     "test";
const char* password = "12345678";

void setup()
{
  WiFi.softAP(ssid, password);
  server.on("/", handleRoot(server));           // <-- use of deleted function 'esp8266webserver::ESP8266WebServerTemplate<WiFiServer>::ESP8266WebServerTemplate(const esp8266webserver::ESP8266WebServerTemplate<WiFiServer>&)'
  server.begin();
}

void loop()
{
  server1.handleClient();
}

Content index.h:

void handleRoot(ESP8266WebServer server);

const char htmlIndex[] PROGMEM = R"=====(

    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>

Hello World!

)=====";

Content index.c:

#include "webpages/index.h"

void handleRoot(ESP8266WebServer server)
{
  Serial.println("GET /");
  server.send(200, "text/html", htmlIndex);
}

How can I use the ESP8266WebServer server created in the main.c in index.c?


texts:
Hi fellow programmers,

I started to program Arduino a little deeply and popped out the following error when I was writing a class to read the pulses of a Hall effect flow rate sensor:

SensorDeVazao.cpp.o: In function `SensorDeVazao::Resetar()':
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
SensorDeVazao.cpp.o:SensorDeVazao.cpp:141: more undefined references to `SensorDeVazao::SensorHandle' follow
collect2: error: ld returned 1 exit status

The code is divided in two files, a *.h and a *.cpp, so it is uncircumstantial to paste the code here (pos-edited: the codes are the following: *.h: codepad.org/UyLfik6W *.cpp: codepad.org/5KJmraCC). But I will explain the context:

SensorHandle is a static object of the own class SensorDeVazao (Brazilian Portuguese to FlowRateSensor) and it is used in an glue function used by the attachinterrupt to read the pulses I've mentioned previously. The function claimed in the error log ("Resetar", Brazilian Portuguese for reset) don't use the variable "SensorHandle". Last but not least, the message shown in the second line appears subsequently multiple times in the error window.

I hope, I provided all the informations to help you solve this issue.
Thank you for the attention.

PS.: Sorry if this is a duplicated post. If yes, please forward it in the comments below.


texts:
avrdude: stk500_getsyn(): not in sync_resp=0*00
avrdude: stk500_disable: protocol error, expect=0*14,resp=0*51

These are the errors occurring when I am trying to upload to the board.
I've tried all the suggestions that suggested in this. When I am trying to burn the bootloader the same error is showing.


texts:
Hy guys,

I am having an issue with my new LCD16x2 display. I connected a potentiometer and read the values. The values are properly read and send to Serial. I also display the values on the display. I am having no issues when increasing the values, but when I go down again at a certain point the displays doesn't display the correct value anymore, but on the Serial I can still see the right readings.

I suppose this has something to do with the display still storing previous values for this digit in the buffer and when I go down the values are not properly reset. But I don't wan't to clear the whole buffer, since then the whole thing just blinks every iteration.

Here's my code

// ESC_Calibration.ino
#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>
#include <Servo.h>

#define WHITE 0x7

Servo firstESC;
Servo secondESC;
int throttlePin = 2;
int firstESCPin = 2;
int secondESCPin = 3;

Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

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

    lcd.begin(16, 2);
    lcd.setBacklight(WHITE);
    lcd.setCursor(0, 0);
    lcd.print("throttle:");

    firstESC.attach(firstESCPin);
    secondESC.attach(secondESCPin);
}

void loop() {
    int throttle = analogRead(throttlePin);
    throttle = map(throttle, 0, 1023, 0, 179);

    lcd.setCursor(0, 1);
        Serial.println(throttle);
        lcd.setCursor(0, 1);
    lcd.print(throttle);

    firstESC.write(throttle);
    secondESC.write(throttle);

    delay(500);
}

Does anyone have a suggestion how to improve this and fix it, so it'll display the right readings, but doesn't blink?

Thanks for your help in advance! :-)


texts: Arduino Uno serial communication using USB-to-TTL converter

texts: How to send data (Hello World) from Arduino Uno to a PC using USB to TTL/UART (PL2303 4 wires)? Why do I need to press the reset button to upload a program using PL2303?


texts: Why do we use bitwise operators to assign PORTx, DDRx and Pinx?

texts:
I have come accross a lot of examples using ways similar to the ones shown below to assign values to the pins.

PORTB |= (1<<PORTB2); //set bit 2

PORTB &= ~(1<<PORTB1); //clear bit 1

DDRD = DDRD | B11111100;  //Sets up the pins for output

My question is why do we need to use bitwise operations to make assignements?


texts: Atmega168A won't be programmed via USB (Minicore)

texts:
I have designed a custom board based on a Atmega168A and a MCP2221 for the USB bridge. I successfully programmed the Atmega168A with an Arduino as ICSP with the following sketch (Minicore Atmega core):

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

void loop() {
  if(Serial.available()) {
    char c = Serial.read();
    while(Serial.available());
    Serial.print("Received:");
    Serial.println(c);
  }
  Serial.println("Loop");
  delay(1);        // delay in between reads for stability
}

Parameters:

Board Atmega168
Clock 8MHz internal
BOD 2.7V
LTO Disabled
Variant 168A
Bootloader Yes
COM port: [ARduino UNO's for programming via UNO, custom board's for programming via USB]
Shift-upload for programming via UNO, upload without shift for programming via USB

Everything works fine: loop, received character, and reset when I flick my on-board switch (SW1 on the schematic below).

However I cannot program the Atmega168A by uploading the sketch via USB. The log output is stuck at:

  Sketch uses 2018 bytes (12%) of program storage space. Maximum is
  15872 bytes. Global variables use 206 bytes (20%) of dynamic memory,
  leaving 818 bytes for local variables. Maximum is 1024 bytes.
  C:\Users\grego\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude
  -CC:\Users\grego\AppData\Local\Arduino15\packages\MiniCore\hardware\avr\2.0.3/avrdude.conf
  -v -patmega168 -carduino -PCOM11 -b38400 -D -Uflash:w:C:\Users\grego\AppData\Local\Temp\arduino_build_665958/DigitalReadSerial.ino.hex:i

  avrdude: Version 6.3-20190619
           Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
           Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Users\grego\AppData\Local\Arduino15\packages\MiniCore\hardware\avr\2.0.3/avrdude.conf"

     Using Port                    : COM11
     Using Programmer              : arduino
     Overriding Baud Rate          : 38400

Even when I flick the switch SW1 to OFF right after compiling nothing happens. I also have tried using a jumper to short RST to GND myself and it's even worse, the log output ends this time with "an error occurred while uploading the sketch: avrdude: ser_open(): can't open device "\.\COM11": Access is denied.] whereas this timing of putting and removing the jumper always worked for me before (with a different core though).

Here is the schematic, all wire labels are net labels.

I had a v1 of the board which I was able to program just fine via USB, the only difference is the change from Attiny841 to Atmega168 and the reset capacitor used to be connected to ground instead of one of the pins of the switch (but I've seen online it should be optional).


texts: Why is the IDE not able to find the board despite it being clearly seen and selected?

texts:
i'm having an odd problem where despite having the correct port selected 3 times i'm still getting an error as shown below:  message:

Arduino: 1.8.9 (Windows 10), Board: "Adafruit Feather M0, Arduino, Off"

Sketch uses 20876 bytes (7%) of program storage space. Maximum is 262144 bytes.
Atmel SMART device 0x10010005 found
Device       : ATSAMD21G18A
Chip ID      : 10010005
Version      : v2.0 [Arduino:XYZ] Mar  5 2016 17:46:52
Address      : 8192
Pages        : 3968
Page Size    : 64 bytes
Total Size   : 248KB
Planes       : 1
Lock Regions : 16
Locked       : none
Security     : false
Boot Flash   : true
BOD          : true
BOR          : true
Arduino      : FAST_CHIP_ERASE
Arduino      : FAST_MULTI_PAGE_WRITE
Arduino      : CAN_CHECKSUM_MEMORY_BUFFER
Erase flash
done in 0.832 seconds

Write 21164 bytes to flash (331 pages)

[=====                         ] 19% (64/331 pages)
[===========                   ] 38% (128/331 pages)
[=================             ] 58% (192/331 pages)
[=======================       ] 77% (256/331 pages)
[============================= ] 96% (320/331 pages)
[==============================] 100% (331/331 pages)
done in 0.128 seconds

Verify 21164 bytes of flash with checksum.
Verify successful
done in 0.016 seconds
CPU reset.
Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.

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


texts: Determine difference between 3.3V and 5V shields

texts:
How do you determine if an Arduino shield uses 3.3V or 5V on their pins?

Previously, I thought all Arduino shields used 5V, since that's what most  Arduinos use. However, I've been researching Arduino-compatible single-board computers like the PCDuino and Galileo, but these all seem to use 3.3V. More confusingly, they're vague about what types of Arduino shields they support. The PCDuino claims to only support 3.3V shields, but has an adapter shield to convert 5V. The Galileo has a jumper to support either 3.3V or 5V shields.

The main problem is how do you determine what voltage level Arduino shields use? I have a Seeedstudio motor shield and a Sain Smart sensor shield, and while they both take 5V power input, the docs don't mention anything about logic voltage level. How do I determine this?


texts: Motor does not work for a specific case when programming with L293D motor driver shield

texts:
I tried to make a car that moves using a 4x4 keypad.
Pressing "12" unlocks the car and sets the motors to move forward. After that, if I press 4, the speed of the left motor is reduced to half allowing the motor to turn left, and vice versa for right wheel when key 6 is pressed.
Here is the code:
#include <Key.h>
#include <Keypad.h>

char* startCar = "12";
int position = 0, state = 0;

/*
 * state 0: off
 * state 1: forward
 * state 2: backward
 *
 */

const byte rows = 3;
const byte cols = 3;
char keys[rows][cols] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'}
};

byte rowPins[rows] = {2,3,4};
byte colPins[cols] = {PD7, PD6, PD5};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, rows, cols);

int a=12,b=11,c=10,d=9;
void setup()
{
  pinMode(a,OUTPUT);
  pinMode(b,OUTPUT);
  pinMode(c,OUTPUT);
  pinMode(d,OUTPUT);
  Serial.begin(9600);
  setLocked(true);
}

void loop()
{
  char key = keypad.getKey();
  Serial.print(key);
  if (key == '9')
  {
    position = 0;
    setLocked(true);
  }
  if (key == startCar[position])
  {
    position ++;
  }
  if (position == 2)
  {
    setLocked(false);
  }
  if(state)
  {
    if(key=='2')
     {
      //Move forward
        state = 1;
        runmotors(255,0,0,255);
     }
     if(key=='8')
     {
      //Move backward
        state = 2;
        runmotors(0,255,255,0);
     }
    if(key == '4')
    {
      if(state == 1)
      {
        runmotors(127.5,0,0,255);
      }

      else if(state==2)
        runmotors(0,127.5,255,0);
    }
    if(key == '6')
    {
      if(state == 1)
        runmotors(255,0,0,127.5);
      else if(state==2)
        runmotors(0,255,127.5,0);

    }
  }
  delay(100);
}

void setLocked(int locked)
{
  if (locked)
  {
    state = 0;
    runmotors(0,0,0,0);
  }
  else
  {
    state = 1; // Moves forward
    runmotors(127.5,0,0,255);
  }
}
void runmotors(int s1,int s2,int s3,int s4)
{
  analogWrite(a,s1);
  analogWrite(b,s2);
  analogWrite(c,s3);
  analogWrite(d,s4);
}

Everything works perfectly, except for the fact that when the state is 1, i.e. car is running forward, and I press 4 the left motor completely stops instead of reduced speed. The LED on the motor driver shield which shows whether a motor is running or not also goes off.
It is not a fault of the motor shield or the arduino as it worked when I test it individually with the motors (i.e. without the keypad etc).
Here is a photo of the shield:

Although my problem is not quite visible in this, but here is a video of the car: https://www.youtube.com/watch?v=bq19gNOL8Pg


texts: Can I use the PWM pins as regular digital input/output pins?

texts: In regards to the arduino which has pwm pins, can I use these pins as normal input/output digital pins or not? Thanks in advance.


texts: How to physically connect the vcc and gnd of multiple sensors to a PCF8574 IO extender board?

texts:
Just starting with Arduino and got my first project working.
I need to expand the number of sensors used and would like to know how to physically connect the vcc and gnd of the sensors to the PCF8574?
Thanks


texts: Where is the inaccuracy of my arduino thermistor circuit coming from?

texts:
I've setup four thermistors and a known resistor in series and connected them to the 3.3V output (as I've heard it's cleaner than the 5V) of an Arduino Uno (with the 3.3V also connected to ARef to increase accuracy), with the four analog inputs testing the voltage drop across each thermistor to determine its resistance, and hence temperature.

But even with no change in the thermistor temperatures, the voltages I get from the arduino vary significantly. See below an example readout of the four arduino inputs (with thermistor temperatures/resistances same throughout):

230 424 634 849

212 412 597 819

241 415 611 857

204 413 654 845

The accuracy I come out with is around 5-10 degrees - way more than I expected. Why is this? And what can I do to get it down to less than one degree? Many thanks

UPDATE:
A MASSIVE THANKYOU to all those who helped me on this, particularly @NickGammon, @Talk2 and most of all @JRobert for the brilliantly clear and simple to follow circuit instructions to follow, all of which helped to thoroughly solve my problem! The sensor works great now, many thanks!!


texts: Wake Huzzah Feather ESP8266 With Reed Switch

texts:
Forgive me if this is a really dumb question but I am new to IOT and hardware in general.

I have a Huzzah Feather ESP8266 and I am trying to make a bathroom occupancy sensor.  I am using a standard reed switch door sensor (example here).

Ultimately what I want this device to do is:

The plan is to wake the device from deep sleep when the door is closed, according to the documentation GPIO16 needs to be connected to RST to send a wake signal.
Once awoken check the reed switch and send a message to Azure IoT hub that says the bathroom is occupied if door is closed.
Put the device into deep sleep, waking every 30 seconds.
Every time the device wakes check the switch, once the door is opened I send a message to Azure that the bathroom is not occupied and then put into deepSleep(0) (i.e asleep until the door is closed again, then the process repeats)

Right now this all works but in the opposite. I can wake the device when the door is opened, the message sends successfully to Azure.

From my super limited understanding of this it seems like what I want to do should be possible.  I imagine I am missing something very simple, but I have hit a wall here.

I dont know how to make wiring diagrams so hopefully a description of my setup will suffice:

GPIO 16: Door sensor wire #2
RST: GPIO 16
GND: Door sensor wire #2

Simplified code sample:

void setup()
{
    initSerial(); //inits serial
    initWifi(); //initis wifi
    door_open(); //sends message
}

void door_open() {
  IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);

  if (iotHubClientHandle == NULL)
  {
    Serial.print("Failed on IoTHubClient_LL_Create\r\n");
  }
  else
  {
    // Because it can poll "after 9 seconds" polls will happen
    // effectively at ~10 seconds.
    // Note that for scalabilty, the default value of minimumPollingTime
    // is 25 minutes. For more information, see:
    // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
    unsigned int minimumPollingTime = 9;

    if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
    {
      Serial.print("failure to set option \"MinimumPollingTime\"\r\n");
    }

    if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
    {
      Serial.printf("failure to set option \"TrustedCerts\"\r\n");
    }

    if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, NULL) != IOTHUB_CLIENT_OK)
    {
      Serial.print("unable to IoTHubClient_SetMessageCallback\r\n");
    }

    IOTHUB_MESSAGE_HANDLE messageHandle;
    if(digitalRead(DOOR) == LOW)
    {
      messageHandle = IoTHubMessage_CreateFromString("closed");
      Serial.println("Door closed");
    }
    else
    {
      messageHandle = IoTHubMessage_CreateFromString("open");
      Serial.println("Door Open");
    }

    if (messageHandle == NULL)
    {
      Serial.print("unable to create a new IoTHubMessage\r\n");
    }
    else
    {
      MAP_HANDLE propMap = IoTHubMessage_Properties(messageHandle);

      if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
      {
        Serial.print("failed to hand over the message to IoTHubClient");
      }
      else
      {
        Serial.print("IoTHubClient accepted the message for delivery\r\n");
      }
      IoTHubMessage_Destroy(messageHandle);
    }

    while (1)
    {
      IoTHubClient_LL_DoWork(iotHubClientHandle);
      ThreadAPI_Sleep(100);
    }
  }
}

To clarify:  Right now my device will wake when the door sensors magnetic parts are separated.  I want the device to wake when the circuit is complete (i.e the sensors are together).


texts: Lego / Meccano style blocks for 'serious' projects

texts: What can be used like Lego or other construction sets, but is more serious and 'professional'?  E.g. what comes with gears and screws and things like that, but is geared to serious modelling or more permanent projects?


texts: Continous running light with fading trail

texts:
In examples of FastLED library, there's the animation of a dot sweeping back and forth, with fading trails (file "DemoReel100", animation "sinelon"). How can I alter the code so instead of moving back, the dot begins at LED #1 again; so when using a LED ring, then the movement is continuous and circular.
Since the code will be part of a more complex project with reading of button states etc, the animation code has to be non-blocking, i.e. delay() is not an option.

void sinelon()
{
fadeToBlackBy( leds, NUM_LEDS, 20);
int pos = beatsin16( 13, 0, NUM_LEDS-1 );
leds[pos] += CHSV( gHue, 255, 192);
}


texts: Arduino receiving values over serial, but not responding

texts:
Now this is gonna make me cry.

Yesterday night, my python script was working perfectly fine, while sending values over serial comm to my Arduino UNO. I have added the 10 microFarad capacitor between the RESET and GND pins. Strangely, any value sent from the Arduino IDE's serial port wasn't working, the Arduino just received the value and sat like nothing happened. Values sent through my script and puTTY worked fine.

Today, same setup, same stuff, same PC, same USB port same everything but the UNO is not responding to any value received from my python script, BUT responds to all values sent from either the Arduino IDE's serial monitor or from puTTY.

What has gone wrong in here? I have connected a 10 microfarad capacitor between the RESET and GND pins.

Here's the Python script -

import numpy as np
import cv2
import serial
ser = serial.Serial('COM3',115200,writeTimeout = 0)
def f(x): return
cv2.namedWindow('Control')

# create trackbars for color change
cv2.createTrackbar('High H','Control',179,179, f)
cv2.createTrackbar('Low H','Control',0,179, f)
cv2.createTrackbar('High S','Control',255,255, f)
cv2.createTrackbar('Low S','Control',0,255, f)
cv2.createTrackbar('High V','Control',255,255, f)
cv2.createTrackbar('Low V','Control',0,255, f)
cv2.createTrackbar('Guassian Blur','Control',0,99, f)

cap = cv2.VideoCapture(0)
while(True):
  ret, image = cap.read()
  HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  # Getting trackbar values
  highH = cv2.getTrackbarPos('High H','Control')
  lowH = cv2.getTrackbarPos('Low H','Control')
  highS = cv2.getTrackbarPos('High S','Control')
  lowS = cv2.getTrackbarPos('Low S','Control')
  highV = cv2.getTrackbarPos('High V','Control')
  lowV = cv2.getTrackbarPos('Low V','Control')
  # Thresholding the image.
  thresh = cv2.inRange( HSV, (lowH, lowS, lowV), (highH, highS, highV))
  blurVal = cv2.getTrackbarPos('Guassian Blur','Control')
  if(blurVal%2==0):
      blurVal=blurVal+1
  thresh_smooth = cv2.GaussianBlur(thresh, (blurVal, blurVal), 0)
  #Defining the kernel to be used for Morphological ops.
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
  # Applying Opening and Closing.
  thresh_smooth = cv2.morphologyEx(thresh_smooth,cv2.MORPH_OPEN,kernel)
  thresh_smooth = cv2.morphologyEx(thresh_smooth, cv2.MORPH_CLOSE, kernel)

  #(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(thresh_smooth)
  eleR = np.count_nonzero(thresh_smooth[0:480, 320:550])
  eleL = np.count_nonzero(thresh_smooth[0:480, 0:320])
  eleO = np.count_nonzero(thresh_smooth[0:480, 550:640])
  if (eleL>eleR and eleL>eleO and eleL!= (eleR+eleO)):
     cv2.putText(image,"Left Turn", (320,240), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
     ser.write('L')
     print ('L')
  elif (eleO>eleR and eleO>eleL):
     cv2.putText(image,"Right Turn", (240,320), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
     ser.write('R')
     print ('R')
  else:
     cv2.putText(image,"Straight", (240,320), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
     ser.write('S')
     print ('S')
  cv2.imshow("BGR", image)
  cv2.imshow("Thresholded", thresh_smooth)
  #print ser.readline();
  if cv2.waitKey(1) & 0xFF == ord('q'):
        break
#cv2.imwrite('ImG.png', thresh_smooth)
cap.release()
cv2.destroyAllWindows()

Here's the Arduino sketch -

#include <Servo.h>
Servo steeringServo;
char data = ' ';
int E1 = 11;
int brake1 = 12;

void setup() {
  steeringServo.attach(9);
  pinMode(E1, OUTPUT);
  pinMode(brake1, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  if(Serial.available()){
    data = Serial.read();
  }
  if(data =='A'){
    steeringServo.write(30);
  }
  else if(data == 'D'){
    steeringServo.write(126);
  }
  else if(data == 'S'){
    steeringServo.write(78);
  }

}


texts: Implement two processes at the same time

texts:
I am a beginner in arduino and due to the lockdown I have been learning it by implementing it on tinkercad. I have made a simulation where I have attached :

Servo Motor

Ultrasonic Sensor

Led Bulb

LCD display

to an arduino uno 3
My AIM :  When something falls under 30cm of the ultrasonic sensor, the servo motor starts from zero position and goes upto 180 degrees in a span of 20seconds and then goes back to its initial position. At the same time and led switches on for 20s and switches off when the motor returns back to its position.
I was able to successfully implement this. But then I added an lcd to show the time i.e time is initialized at 0seconds and then goes to 20 seconds and when the motor resets. Time also resets.
I was able to make a timer on another simulation and I tried to run it in this one by placing the code correctly but I am not able to figure out how?
The present code I have written keeps blinking the led at an interval of one second and the servo moves very very slowly.
Any sort of help will be amazing.
This is my simulation, I have made it public, you may copy and simulate it if you have a tinkercad account. Even without an account you can see how it looks.
Here is the code:
(Please ask if you want me to add comments some areas)
//library code for lcd
#include <LiquidCrystal.h>
//setting up pins
const int rs = 9, en = 8, d4 = 5, d5 = 4, d6 = 3, d7 = 2;

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

unsigned long readTime=20;

//servo motor
#include <Servo.h>
Servo servo_9;
int pos = 0;
//servo motor end

//ultrasonic sensor pin
const int pingPin = 12;

//lcd
signed short seconds;
char timeline[16];

void setup()
{

  servo_9.attach(13); //servo pin
  Serial.begin(9600);

  pinMode(11,OUTPUT);// led

  //lcd initialize
  lcd.begin(16, 2);
  lcd.print("Time : ");

}

void loop()
{

  long duration, cm;
  //Ultrasonic start
  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  cm = microsecondsToCentimeters(duration);

  // Print the distance
  Serial.print("Distance: ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  // ultrasonic end

  // the servo motor should activate when object is
  //less than 30cm close to the sensor

 if(cm < 30) {

  // sweep the servo from 0 to 180 degrees in steps
  // of 1 degrees
  for (pos = 0; pos <= 180; pos += 1) {

    // tell servo to go to position in variable 'pos'
    servo_9.write(pos);

     //LCD TIMER START
    lcd.setCursor(0, 1);
    sprintf(timeline,"%0.2d secs", seconds);
    lcd.print(timeline);
    delay(1000);
    seconds++;

    //led buld switch on
    digitalWrite(11,HIGH);

    // wait 20ms for servo to reach the position
    delay(200);

    //switch of the bulb
    digitalWrite(11,LOW);

  }

  //moving servo back to zero
  for (pos = 180; pos >= 0; pos -= 1) {
      // tell servo to go to position in variable 'pos'
      servo_9.write(pos);
      // wait 20 ms for servo to reach the position
      delay(20); // Wait for 15 millisecond(s)
            }

    } //if end

  delay(100);

}//loop end

//FUNCTIONS

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}


texts: I have been awaiting the release date for some time for the Arduino TRE.  So, my question is simple does anyone know the release date or any hints about when it might come out?  Also, what do you think the cost will be?


texts: Replicate a Waveform Exactly with An Arduino Uno

texts:
So I've got a waveform that's high for 16ms and low for 2ms repeating forever. I need to recreate that and offsets of that waveform time exactly on a different pin. Right now, I've got an interrupt on the rising edge for the 16ms low/high transistion, and delayMicroseconds() that determines the offset and duration of the high and low pulses. Trouble is, I'm not sure the code I have is as fast and accurate as it could be. And the replicated waveform seems to shift through the full period of the original one. I need it to be locked in.Any suggestions?
Here is the code:

 //3 is interrupt for Timing
//4 through 11 are Time dependent receivers
//3-11 Pins 12-19
char incomingByte = 0;

int pins[9] =
{
  3,4,5,6,7,8,9,10,11
};

void timing()
{
  //Serial.println("This is a 0ms Event");
 // if(Serial.available() > 0)
 // {
    incomingByte = Serial.read();
    Serial.print("I received");
    Serial.println(incomingByte);

     pinMode(10, OUTPUT);
     digitalWrite(10, HIGH);
     delayMicroseconds(16000);
      digitalWrite(10, LOW);
      delayMicroseconds(2000);
      digitalWrite(10, HIGH);
 }
//}

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

for(int i=0;i<8;i++)
{
  pinMode(pins[i], INPUT);
}
pinMode(3,INPUT);
attachInterrupt(1,timing,RISING);

//Begins Serial
Serial.begin(115200);
}

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

Here's the waveform I'm trying to duplicate:


texts: Remote Controlled Self-Balancing Robot - how to mix control input with IMU input?

texts:
I'm building a two-wheeled, self-balancing, remote-controlled robot. I'm familiar enough with the IMU and PID to get it working to just stand up but I need to drive it via remote control.

I've got no code written yet; trying to understand the concepts before diving in.

This much I understand: [IMU] -> [Kalman filter] -> [PID] -> [Motors]

Where I'm getting tripped up is where to mix the RC component into that control chain?


texts: Im using Arduino connected to an SD card and PIR sensor , and based on the inputs from the PIR sensor the data needs to be written on the sd card , It is done , but for retrieving the data from the SD card is there any library for arduino ? Ive seen Extended Database library ,since im retieving huge amount of data from the SD card and i should be able to do Lots of sorting operations based on the CSV values in the file , So can i do Sorting operations in  Extended Database library from an Sd card ive seen the Examples but it doesnt have any sorting operations ,Is Querying data from the SD card using this library is Possible ?ie)Selecting data Based on some Conditions even if it can be done is there any tutorial ? Or is there any other alternative Library? for this purpose . Thank You


texts:
Summary

I'm having problems with my RTC draining its coin cells quickly - fresh batteries are drained in a few months. The RTC is set to signal an interrupt every 5 minutes, and I wonder - if there is no other power attached to the circuit, is that enough to drain the coin cell?

Details and my troubleshooting:

Problems with my RTC - if I leave the circuit unpowered for a few days (so that the only power to the RTC is from the coin cell backup), the time resets to 00:00 January 1, 2000. This doesn't happen immediately when I unplug it. If I disconnect it from the computer, plug it back in the next day, the time is ok. If I leave it unplugged for a few days, then plug it in, the date is reset.

This suggests the battery is bad. So I tested it with my meter (and an 100 ohm load, as described here: https://www.youtube.com/watch?v=HcikzMG7mMU). And sure enough, the batter has dropped quite a bit from its 3V start value.

That's all good, except that this battery is only a few months old, and it should last for years in an RTC. I've got two batteries purchased in the last year and used in RTC modules, and both are now drained.

My current hypothesis is that, after I unplug my circuit from the computer, the RTC continues to run on the coin cell, firing interrupts every 5 minutes, and it is these interrupts that are causing the drain. Does this make sense? If not, what else could I check?

Setup

Breadboard arduino, DS3231 RTC on a breakout, connected

RTC SDA -> Arduino A4
RTC SCL -> Arduino A5
RTC GND -> Common GND
RTC VCC -> Common 5V (from ftdi/USB cable, when plugged in)
RTC SQW -> Arduino D2

The RTC is 'active-low', and the SQW pin is held at 5V between interrupts. With my multimeter, the brief drop to 'LOW' is undetectable. I also can't detect any current flow from the SQW pin with my multimeter.

Sketch

Including only the code related to the RTC (SD card and temperature bits removed).

/*-(Import required libraries)-*/
#include <Time.h>
#include <DS3232RTC.h> //source: https://github.com/JChristensen/DS3232RTC

/*-( Declare Constants )-*/
const int wakeUpPin = 2;
#define resolution 5 // frequency in minutes to wake from sleep

/*-(Declare Variables)-*/
time_t t;
int nextLoop;

/****** SETUP: RUNS ONCE ******/
void setup()
{
  Serial.begin(9600);

  Serial.println();
  pinMode(wakeUpPin, INPUT);

  t = RTC.get();

  nextLoop = ((minute(RTC.get()) / resolution) + 1) * resolution;
  if (nextLoop >= 60) {
    nextLoop -= 60;
  }
  Serial.print(RTC.temperature());
  Serial.print(",");
  Serial.print(RTC.oscStopped());
  Serial.print(",");
  Serial.println(nextLoop); // the minutes when the next reading will be taken

}

/****** LOOP: RUNS CONSTANTLY ******/
void loop()
{
  t = RTC.get();

  Serial.print(year(t), DEC);
  Serial.print("/");
  Serial.print(month(t), DEC);
  Serial.print("/");
  Serial.print(day(t), DEC);
  Serial.print(",");
  Serial.print(hour(t), DEC);
  Serial.print(",");
  Serial.print(minute(t), DEC);
  Serial.print(",");
  Serial.print(second(t), DEC);
  Serial.print(",");

  goToSleep();
}

void goToSleep(void) {
    Serial.print("Sleeping until: ");
    Serial.println(nextLoop);
    Serial.flush();
    RTC.setAlarm(ALM2_MATCH_MINUTES, nextLoop, 1, 1);
    RTC.alarmInterrupt(ALARM_2, true);
    attachInterrupt(0, wakeUp, LOW);

    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
    detachInterrupt(0);
    RTC.alarm(ALARM_2);
    nextLoop += resolution;
    if (nextLoop >= 60) {
         nextLoop -= 60;
    }
}

void wakeUp(){
  // Handler for the pin interrupt.
}


texts:
I'm trying to get AFMotor.h working on an Arduino Uno Wifi Rev2 with a L293D Motor Shield.
However, when I install the library (regardless of whether I do it using the in-built library manager or by downloading a zip and moving it to the relevant folder), the following errors get thrown on compilation.
In file included from c:\users\charya\documents\arduinodata\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino5\avr\include\avr\io.h:99:0,
                 from c:\users\charya\documents\arduinodata\packages\arduino\tools\avr-gcc\7.3.0-atmel3.6.1-arduino5\avr\include\avr\pgmspace.h:90,
                 from C:\Users\Charya\Documents\ArduinoData\packages\arduino\hardware\megaavr\1.8.6\cores\arduino/api/String.h:31,
                 from C:\Users\Charya\Documents\ArduinoData\packages\arduino\hardware\megaavr\1.8.6\cores\arduino/api/Print.h:24,
                 from C:\Users\Charya\Documents\ArduinoData\packages\arduino\hardware\megaavr\1.8.6\cores\arduino/api/Stream.h:25,
                 from C:\Users\Charya\Documents\ArduinoData\packages\arduino\hardware\megaavr\1.8.6\cores\arduino/api/Client.h:22,
                 from C:\Users\Charya\Documents\ArduinoData\packages\arduino\hardware\megaavr\1.8.6\cores\arduino/api/ArduinoAPI.h:29,
                 from C:\Users\Charya\Documents\ArduinoData\packages\arduino\hardware\megaavr\1.8.6\cores\arduino/Arduino.h:23,
                 from sketch\code.ino.cpp:1: C:\Users\Charya\Documents\Arduino\libraries\afmotor/AFMotor.h:49:30: error: 'CS01' was not declared in this scope
     #define MOTOR34_8KHZ _BV(CS01)              // divide by 8
                              ^ C:\Users\Charya\Documents\Arduino\libraries\afmotor/AFMotor.h:52:33: note: in expansion of macro 'MOTOR34_8KHZ'
     #define DC_MOTOR_PWM_RATE   MOTOR34_8KHZ    // PWM rate for DC motors
                                 ^~~~~~~~~~~~ C:\Users\Charya\Documents\Arduino\libraries\afmotor/AFMotor.h:156:47: note: in expansion of macro 'DC_MOTOR_PWM_RATE'    AF_DCMotor(uint8_t motornum, uint8_t freq = DC_MOTOR_PWM_RATE);
                                               ^~~~~~~~~~~~~~~~~ C:\Users\Charya\Documents\Arduino\libraries\afmotor/AFMotor.h:49:30: note: suggested alternative: 'B101'
     #define MOTOR34_8KHZ _BV(CS01)              // divide by 8
                              ^ C:\Users\Charya\Documents\Arduino\libraries\afmotor/AFMotor.h:52:33: note: in expansion of macro 'MOTOR34_8KHZ'
     #define DC_MOTOR_PWM_RATE   MOTOR34_8KHZ    // PWM rate for DC motors
                                 ^~~~~~~~~~~~ C:\Users\Charya\Documents\Arduino\libraries\afmotor/AFMotor.h:156:47: note: in expansion of macro 'DC_MOTOR_PWM_RATE'    AF_DCMotor(uint8_t motornum, uint8_t freq = DC_MOTOR_PWM_RATE);
                                               ^~~~~~~~~~~~~~~~~ exit status 1 Error compiling for board Arduino Uno WiFi Rev2.

I've also attached an image of the error if that's easier to read. I have no code written, and I am only importing the library and compiling it.
What am I doing wrong? I'm unsure what's even happening.


texts: Can I program AVR Microcontrollers using Arduino Development board with AVR Studio?

texts: I know and I can program any AVR microcontroller with Arduino IDE and Arduino Uno board. Can I use Arduino board with AVR Studio? Or I have to buy an AVR Development board?


texts: The right way to find and understand the libraries

texts:
I am working on a project to send sensor values from esp8266's Wemos D1 mini to MySQL.
I tried using the library MySQLconnection.h but I couldn't make it to connect to wifi. So I uploaded a simple program to connect the board to WiFi using ESP8266.h but I got the error that Unable to compile for Wemos D1 board.

Please tell me the right procedure to select the right library for the problem defined.


texts: Grounding issues Arduino Ethernet Shield makes WS2811 LEDs flicker

texts:
I have an Arduino Due with an Arduino Ethernet Shield V2 that I use to control multiple daisy-chained WS2811 LED strips.

When I turn on most of the LEDs the Arduino and attached wires seem to become an antenna, picking up fluctuations that make the LEDs flicker, by messing with the data on the WS2811 data line. Touching the data cable, touching the ethernet plug on the shield, or simply hovering my hand over the Arduino adds noise that causes flickering in the lights.

When I pull out the ethernet plug, it stops. (The Arduino continues to update the WS2811 chips, even without network connection)

The flickering is especially strong when I set the first couple of LEDs in the chain to White (biggest draw of current), while having red or green colored LEDs at the beginning causes milder flickering (even if there are LEDs set to White further back in the chain).

Some more observations:

The LED strips are powered from both sides. It doesn't seem to be a power issue.
I tried with a different Arduino Due, a different Ethernet shield, a different router and Ethernet cable, and a different power supply.
The router the Arduino is plugged into, is positioned on the same table, and powered from the same power bar as the LED/Arduino power supply.
I tried running the Arduino and the LEDs from different power supplies but that didn't help. Rather the opposite (which makes sense)
This happens no matter how long the equipment has already run or how hot it is.

Another mystery:
You might notice the lose ground cable from the LED strip connector. When I plug that into the Arduino Due, the LEDs don't get turned on at all. When I plug that ground cable into the Ethernet shield sitting on the Due, then some lights turn on wrong. No matter if Ethernet is plugged in or not (though there's a difference in the 'wrongness' of the lights when Ethernet is plugged in). Note, that the Arduino and the LED strips already share ground 1 foot away as they are both fed by the same 12V power supply.

Where are all these grounding issues coming from and how do I get rid of them? What else could I try?


texts: How to control an Arduino connected device accross the Internet?

texts:
Actually i am trying to do IoT based work.

Until now the sensed data(temperature and humidity) has been made available to only for one user on the Internet using Apache tomcat. So far we have just created a one way communication link between the sensor node and the Internet through the PC.

Now I need to control a device (say a fan) according to the variation with sensed temperature from anywhere through the internet. For the HTML I have used Java Script, which I am new to.


texts: Converting human readable date to a unix timestamp

texts:
Can anyone provide a sample code that would convert a human readable date like 2019-10-27 22:10:35 to a unix timestamp like 1572214235?

I found many topics about it, but they eider refer to out of date libraries, or they seem to address more complex time functions, I find it hard to extract this functionality from them.


texts: How can I read the data stored in EEPROM although is powered OFF based on the simple code I wrote?

texts:
I need help regarding on EEPROM library. Based on the code below, for every 2 sec, I want to store the int for increase where it will keep increasing by 1. Then, I upload to my Arduino Nano and open Serial Monitor to let it run for about 20 seconds. The serial monitor shows that Increase Count:10.
Then I unplug the Arduino Nano, closed the Serial Monitor, wait for 5 sec, then plug back to computer and turn on the Serial Monitor, then the Serial Monitor start to shows Increase Count:1, which indicated it start to recount again from 1,2,3,4.....
I thought that EEPROM will store the last number it counted which is 10, then when I unplug and plug back it should continue to count from 10, 11, 12, .......
So I would like to ask community whether my execution code and the method is correct or not. If not, can you advice me on how I can execute it correctly. Thank you in advance!
#include <EEPROM.h>

int addr=5;
int storagedata;
int increase;

void setup()
{
  storagedata=EEPROM.read(addr);
  Serial.begin(9600);

  timevalue=millis();
}

void loop()
{
  if (millis()-timevalue>=2000)
  {
    increase=increase+1;

    EEPROM.update(addr,increase);
    storagedata=EEPROM.read(addr);

    Serial.print("Increase Count:");
    Serial.println(storagedata);

    timevalue=millis();
  }
}