texts: 'Serial1' was not declared in this scope for automatic plant watering

texts:
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
int in1 = 2;
int in2 = 3;
LiquidCrystal lcd(14,15,16,17,18,19);
int led = 13;
int flag = 0;
int motorpin = 11;
int sensorpin = 7;

void setup()
{
  lcd.begin(16,2);
  Serial1.begin(9600);
  pinMode(led, OUTPUT);
  pinMode(motor, OUTPUT);
  pinMode(sensor, INPUT_PULLUP);
  lcd.print("Plant Watering");
  lcd.setCursor(4,1);
  delay(2000);
  lcd.clear()
  lcd.print("RCC INSTITUTE");
  lcd.setCursor(0,1);
  lcd.print("Starting....");
  delay(2000);
  gsmInit();
  lcd.clear();
  lcd.print("System Ready");
}

void loop()
{
  lcd.setCursor(0,0);
  lcd.print("Automatic Mode");
  if (digitalRead(sensor) == 1 && flag == 0)
  {
    delay(1000);
    if (digitalRead(sensor) == 1)
    {
      digitalWrite(led, HIGH);
      sendSMS("Low Soil Moisture detected. Motor turned ON");
      lcd.begin(16, 2);
      lcd.setCursor(0, 1);
      lcd.print("Motor ON ");
      digitalWrite(motor, HIGH);
      delay(2000);
      flag=1;
    }
  } else if(digitalRead(sensor) == 0 && flag == 1)
  {
    delay(1000);
    if (digitalRead(sensor) == 0)
    {
      digitalWrite(led, LOW);
      sendSMS("Soil Moisture is Normal. Motor turned OFF");
      digitalWrite(motor, LOW);
      lcd.begin(16, 2);
      lcd.print("Motor OFF");
      lcd.setCursor(0, 1);
      lcd.print("Motor OFF");
      delay(2000);
      flag = 0;
    }
  }
}

void sendSMS(String msg)
{
  lcd.clear();
  lcd.print("Sending SMS");
  Serial1.println("AT+CMGF=1");
  delay(500);
  Serial1.print("AT+CMGS=");
  Serial1.print('"');
  Serial1.print("+918xxxxxxxxx"); // number
  Serial1.print('"');
  Serial1.println();
  delay(500);
  Serial1.println(msg);
  delay(500);
  Serial1.write(26);
  delay(1000);
  lcd.clear();
  lcd.print("SMS Sent");
  delay(1000);
  lcd.begin(16, 2);
}

void gsmInit()
{
  lcd.clear();
  lcd.print("Finding Module..");
  boolean at_flag = 1;
  while (at_flag)
  {
    Serial1.println("AT");
    while (Serial1.available() > 0)
    {
      if (Serial1.find("OK"))
      at_flag = 0;
    }
    delay(1000);
  }
  Serial1.println("ATE0"); //<=== it says 'Serial1' was not declared in this scope
  lcd.clear();
  lcd.print("Finding Network..");
  boolean net_flag = 1;
  while(net_flag)
  {
    Serial1.println("AT+CPIN?");
    while(Serial1.available() > 0)
    {
      if (Serial1.find("READY"))
        net_flag = 0;
      break;
    }
    delay(1000);
  }
  Serial1.println("AT+CNMI=2,2,0,0,0");
  delay(1000);
  Serial1.println("AT+CMGF=1");
  delay(1000);
  Serial1.println("AT+CSMP=17,167,0,0");
  lcd.clear();
  Serial1.flush();
}


texts: Prevent reiteration of loop instruction in Arduino/Execute instruction via off switch

texts:
I'd like to make an Arduino play a (2sec).wav file once when it is powered on (via push button) and another when it is switched off i.e. when the push button is pushed there is a 2sec delay and the .wav file plays, then the arduino turns off.  What would the best way be to implement this?  So far I've come up with:

void loop()
{
//play .wav file

while(1){}
}

or:

void setup(){
//play .wav file
}

void loop(){
//empty
}


texts:
So I have 7 different sensor I’d like to send to Processing, then use each of their values as variables inside different webcam filters.

I’m going off of this tutorial which has been helpful, but it doesn’t give linear steps – more like different techniques depending on what you’re trying to use it for.
In that tutorial, it shows two ways to initialize connection between Serial and Arduino – the Punctuation method and the Call-and-response method. I used the Punctuation method.

To sum up the Punctuation method, you put the sensor values into one string, separated with commas. Once the values are sent over, you split the string and put all of the values into an array. Once in an array, you can individually take out each of the values and turn them into variables that are usable in the draw loop.

My Processing sketch runs perfectly fine sometimes. Otherwise it will give either this error :

  Error, disabling serialEvent() for /dev/cu.usbmodem1421
  null

Or this one :

Does anyone see anything fishy with the syntax or structure I’m setting up?
(I took out all filter functions except the temp -> blur to make debugging easier.)

// get the serial lib :
import processing.serial.*;

// give port a variable :
Serial port;

// get the webcam lib :
import processing.video.*;

// give webcam a variable :
Capture webcam;

// sensors
int cap1, cap2, piezo, temp, axisX, axisY, axisZ;

void setup() {
  size(480, 360, P2D);
  smooth();

  webcam = new Capture(this, width, height, 24);
  webcam.start();

  String portName = "/dev/cu.usbmodem1421";
  port = new Serial(this, portName, 9600);
  //port.bufferUntil('\n');
}

void captureEvent(Capture webcam) {
  webcam.read();
}

void serialEvent(Serial port) {

  String reading = port.readStringUntil('\n');
  if (reading != null) {
    reading = trim(reading);

    int values[] = int(split(reading, ','));

    for (int valNum = 0; valNum < values.length; valNum++) {
      print(values[valNum] + "|");
    }
    println();

    if (values.length > 1) {
      cap1 = values[0];
      cap2 = values[1];
      piezo = values[2];
      temp = values[3];
      axisX = values[4];
      axisY = values[5];
      axisZ = values[6];
    }
  }
}

void draw() {

  // temp
  float t;
  if (temp >= 100) { //when analog pin unplugged
    t = 6;
  } else {
    t = 0;
  }

  image(webcam, 0, 0);
  filter(BLUR, t);
}

//if down key pressed, saveImage();
void saveImage()
{
  saveFrame("images/captured-####.jpg");
}

void keyPressed() {
  if (key == CODED) {
    if (keyCode == DOWN) {
      saveImage();
    }
  }
}

I’m thinking it’s an issue with memory, or maybe the way I’m sending/receiving the data is shoddy.

Apparently one of the disadvantages to using Punctuation rather than Call-and-response is that it can slow down the program if it contains a lot of graphic work… but why would it work in perfect time sometimes and then not work at all?

Any insight would be amazing!!


texts:
I understand why servos and motors require an external power source when run from the Uno, but I've seen a lot of tutorials (for example, this one), where the servo is connected directly to the Arduino's 5V port. I did this, and I think it fried my servo. This is also the method shown on the official Arduino tutorials for Knob and Sweep. In fact, the knob tutorial was the first and last tutorial I tried with my servo -- after trying it, the servo didn't work.

It went like this:
1) Try sweep code without using external supply. Works fine.
2) Try knob code without using external supply. Servo hums without moving and heats up (a lot).

Why do tutorials say to do this if it's not advisable?


texts: Can someone help me with my arduino and relay and switch?

texts:
This is my code. What i want to do is activate the relay when switchInNcPin is activate. I am using a switch (micro switch). It has COM NC and NO pins. Can you tell me what is wrong with my code?
PROBLEM:
The relay keeps clicking ON and OFF even though it is meant to wait 5000ms, activate, wait 3000ms, deactivate only once. Can you look at my code and help me?


texts: I want to control my Adruino through Internet without Ethernet or wifi shield. So what are the ways I can do?


texts: Creating a router with ESP32 and SIM800c

texts:
I am trying to create a device which is a combination of ESP32 and Sim800c.
This device (Master) will start AP mode on ESP32, so that other devices (Nodes) will connect to this AP. The Sim800c will provide 2G internet connection to the ESP32.
The nodes will be executing a HTTPS request and via this device (Master) the http request will gets executed and the response will be received via the Master device and again forwarded to the Node.

Basically this device which i am trying to create will act as a WiFi router which provides internet connection to the Nodes.

Hence my question is, will this device work as expected.


texts: Arduino Due as Triggered DMA SPI Slave is possible?

texts:
Is it possible for arduino Due to act as DMA-SPI-slave device which can exchange SPI data (uint16_t TX[10] and RX[10]) in triggered slave mode?

I have a setup in which time period is very short (~500uS/cycle). so I need to exchange data with another Microcontroller (acting as 'Master') within the mensioned time limit. Some other tasks are also to be processed. This is why I have to go for DMA and fast data transfer without intervension of processor. All the codes available are to be used in Master mode of SPI. Not a single one is in SLAVE mode.
I wrote a code but I cannot implement a transfer triggered by SPI hardware. Also how to implement data transfer complete Interrupt after all 10 datas(16bit) have been transferred and received?
Here is my initialization code:

    void DMAslaveBegin()
{
    // Configure the pins for SPI in peripheral mode
    PIO_Configure(
        g_APinDescription[PIN_SPI_MOSI].pPort,
        g_APinDescription[PIN_SPI_MOSI].ulPinType,
        g_APinDescription[PIN_SPI_MOSI].ulPin,
        g_APinDescription[PIN_SPI_MOSI].ulPinConfiguration);
    PIO_Configure(
        g_APinDescription[PIN_SPI_MISO].pPort,
        g_APinDescription[PIN_SPI_MISO].ulPinType,
        g_APinDescription[PIN_SPI_MISO].ulPin,
        g_APinDescription[PIN_SPI_MISO].ulPinConfiguration);
    PIO_Configure(
        g_APinDescription[PIN_SPI_SCK].pPort,
        g_APinDescription[PIN_SPI_SCK].ulPinType,
        g_APinDescription[PIN_SPI_SCK].ulPin,
        g_APinDescription[PIN_SPI_SCK].ulPinConfiguration);
    PIO_Configure(
        g_APinDescription[PIN_SPI_SS0].pPort,
        g_APinDescription[PIN_SPI_SS0].ulPinType,
        g_APinDescription[PIN_SPI_SS0].ulPin,
        g_APinDescription[PIN_SPI_SS0].ulPinConfiguration);
    //pmc_enable_periph_clk(ID_SPI0);
#if USE_SAM3X_DMAC
    pmc_enable_periph_clk(ID_DMAC);
    DMAC_Disable();
    DMAC->DMAC_GCFG = DMAC_GCFG_ARB_CFG_FIXED;  //Fixed priority arbiter
    DMAC_Enable();

#if USE_SAM3X_BUS_MATRIX_FIX    // not active here
    MATRIX->MATRIX_WPMR = 0x4d415400;
    MATRIX->MATRIX_MCFG[1] = 1;         //Single Access
    MATRIX->MATRIX_MCFG[2] = 1;         //Single Access
    MATRIX->MATRIX_SCFG[0] = 0x01000010;
    MATRIX->MATRIX_SCFG[1] = 0x01000010;
    MATRIX->MATRIX_SCFG[7] = 0x01000010;

#endif  // USE_SAM3X_BUS_MATRIX_FIX
#endif  // USE_SAM3X_DMAC
    //  initialize SPI controller - Slave mode
    SPI.begin(_pin);
    SPI_Disable(SPI0);
    REG_SPI0_CR = SPI_CR_SWRST;     // reset SPI
    REG_SPI0_CR = SPI_CR_SPIEN;     // enable SPI
    REG_SPI0_MR = 0x10;              // DLYBCS=0, PCS=0, MODFDIS=1, PS=0, MSTR=0(slave)
    REG_SPI0_CSR = 0x80;            // DLYBCT=0, DLYBS=0, SCBR=0, 16 bit transfer, Mode 0/1
    REG_SPI0_IDR = ~SPI_IDR_RDRF;
    REG_SPI0_IER = SPI_IDR_RDRF;
    NVIC_EnableIRQ(SPI0_IRQn);
    SPI_Enable(SPI0);
}

Is this a valid condition for DMA?
How can I utilize SPI ISR handler like system in DMA for my code so that the complete transaction (simultaneous Transmit & Receive) becomes fully automatic without processor utilization?


texts:
I've got the following:

#include <SoftwareSerial.h>

const int rx = -1;
const int tx = 4;

SoftwareSerial mySerial(rx, tx);

void setup()
{
  mySerial.begin(2400);
  pinMode(tx, OUTPUT);
}

void loop()
{
  if(mySerial.available())
  {
    String data = "Hello World";

    for(int k = 0; k < data.length(); k++ )
    {
      mySerial.write(0xAA);
      mySerial.write(data[k]);
    }

    mySerial.write(0xA9);
  }

  delay(1000);
}

Which I'm trying to send to to a RF transmitter module. It all compiles just fine, but am I forgetting something? And does pin 4 = physical pin 3?


texts:
I was surprised that this question had no answer on Stack Exchange and I can't find much about it elsewhere so, in the hopes that it will be useful to people other than myself, I'd like to ask:
How can one power two arduinos using the same power source? Such that the first is connected by barrel jack to a 12v transformer.
I saw this youtube video which very briefly mentions doing this by make the connections:

Ardu1 --> Ardu2
5V --> 5V
GND --> GND

This surprised me as I was not aware the 5V could operate as a power input. I was expecting the use of the VIN pin somewhere along the line.
Am I correct in thinking that the second arduino would take power on it's VIN pin from 5V on arduino one?
If so, where should the second arduino ground to?


texts:
Im building an electrical system for my EBike.  My bike has 2 power sources, one is the 48 volt battery, the other is a 12 power converter coming off the battery pack.  I need an arduino shield that has 4 switching channels.  2 that can take in the 48 volt and switch it on and off, and two that can take in the 12 volt and switch it on and off.  Something that can take the 12 volt to power the arduino uno would be nice but I can find a chip to do that if necessary.

Since these are lights, normally off would be more more efficient but with the power consumption we are talking about, i can probably run the battery all day to the point of dry and the fets eat all of 50 feet worth of power staying closed.

Does anyone know of anything like that?  I found several shields out there like this but all of them seem to be setup to take 1 voltage input and switch it between the 4 or 6 fets on the board, not different voltages per fet and since I'm a programmer, not an EE so I have trouble reading the schematics.

Because my grounds have to be tied, its easier to switch the positive on and off than the negative.


texts: How to program an Arduino Uno to collect data using a timer interrupt and analyze that data in matlab?

texts:
I working on a project where I want to collect sensor data (from a sensor) and I want to analyze the first 20 data sample (e.g., find the range, trendline e.t.c.). I know how to compile a timer interrupt in Arduino IDE (using an ISR timer), but how would I be able to do this something similar (ISR timer) in MATLAB. The reason being, I want to collect my sensor data at exactly 20 Hz and using a delay function can prove to be inaccurate. Also, when I run a sample program that collects data in MATLAB, my sample frequencies change from 15Hz to even 24Hz (as shown below) . Does anyone have any suggestion on how I can do this? If the question is not clear enough I can elaborate more in the comments.
This is my MATLAB code:
clear all;
a = arduino('com4', 'uno');
i = 0;
v1 = zeros(1e4,1);
v2 = zeros(1e4,1);
x = zeros(1e4,1);
t = timer('TimerFcn', 'stat=false; disp(''Timer!'')',...
                 'StartDelay',5,'Period', 1);
start(t)

stat=true;
tic
while(stat==true)
   %while i<60
    i = i + 1;
    v1(i) = readVoltage(a, 'A0');
    v2(i) = readVoltage(a, 'A1');
    x(i) = i;
    disp(x(i));
    pause(.00001);

  % end
end
toc

% %Plot voltage versus time
v1 = v1(1:i);
v2 = v2(1:i);
x = x(1:i);

p = v1;
n = v2;
%Plot voltage versus time
figure(1);
plot(x,p,'-',x,n,'-')
xlabel('Elapsed time (sec)')
ylabel('v')
title('Ten Seconds of voltage Data')
%set(gca,'xlim',[t(1) t(i)])
legend('v1', 'v2');

%
delete(t) % Always delete timer objects after using them.

Output is
>> Timer
     1

     2

     3

     4

     5

     6

     7

     8

     9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

Timer!
    76

Elapsed time is 5.032553 seconds.
>>

I apologize for the long output. But as you can see, I specified a pause time of .00001, which should give me well over a 20Hz sampling frequency. But I only get 76 samples/5 seconds = 15.2Hz. Also, sometime when I run this the program may collect 79sample/5secons, or even  121sample/5seconds. It just is not consistent. I was hoping to solve this with a timer interrupt that will be hard coded in MATLAB to collect data at exactly 20Hz. Please let me know what y'all think. Thank you.


texts: How to get 38 Khz clock from Timer 0/2 in Arduino Mega 2560?

texts:
I have been trying to generate a PWM wave of 38 Khz (13 microsec= ON period , 13 microsec= OFF period).  Currently I am using Timer 0 to generate the PWM wave , however i am confused as to how to prescale the 16Mhz input clock frequency so that i can get 38 Khz from it .

The code is as follows -

#include<avr/io.h>
#include<util/delay.h>

uint8_t  dutycycle;
void pwm_init()
{
        // Configure PB.7 as output pin
        DDRB |= (1<<PB7);
        DDRG |= (1<<PG5);

        // Clear o/p on Match and Fast PWM Mode
        TCCR0A |=(1<<COM0A1) | (1<<WGM01) | (1<<WGM00) | (1<<COM0B1);// COM0A1/0b1 are the ouput ports , and WGM01 and WGM02 are used for fast PWM mode
        TCCR0B |=(1<<WGM02) | (1<<CS01);//WGM02 is used to set the fast pwm mode with max value stored in OCRA. CS01 is used to prescale the clock frequency to 16Mhz % 8 .
        OCR0A = 52;

}
void dutycycleA(uint8_t dutycycle)
{
    OCR0B = (dutycycle * 52)/100 ;
}
int main()
{
        pwm_init();

        while(1)
        {
            dutycycle=50;
            dutycycleA(dutycycle);
            _delay_ms(1000);
        }
}

So , the code is supposed to keep checking the value of OCR0B with the timer value and if it is less than that , then the output is logic HIGH , and if it is same as the timer value , then it'll be logic LOW . the duty cycle is given as 50 so that a pulse waveform of 50% duty cycle is reached .

However I am unable to obtain 38Khz output .

Please help me figure out where I have gone wrong and also suggest corrections to my approach , if wrong .

Thank you .

PS - I am using Eclipse Neon platform.


texts: Is possible to process analogue inputs with variation frequencies in MHz?

texts:
Is it possible for Arduino boards to accurately process analog inputs that vary at MHz frequencies?

If possible, which Arduino board would be most appropriate for such application?

What adjustments would be required for it to handle such rapid analog input variations?


texts:
I am trying to make Arduino Uno to act as a keyboard. I have successfully flashed the USB-HID firmware in it using this link also and programmed it like this.

uint8_t buf[8] = {
 0
};

int inpin1 = 7;
int inpin2 = 8;
int val1 = 0;
int val2 = 0;

void setup() {
  Serial.begin(9600);
  delay(200);
  pinMode(inpin1, INPUT);
  pinMode(inpin2, INPUT);
}

void loop() {
  val1 = digitalRead(inpin1);
  if(val1 != HIGH) {
   buf[2] = 80; // Left Arrow
   Serial.write(buf, 8);
   releaseKey();
  }
  val2 = digitalRead(inpin2);
  if(val2 != HIGH) {
    buf[2] = 79; // Right Arrow
    Serial.write(buf, 8);
    releaseKey();
  }
}

void releaseKey() {
  buf[0] = 0;
  buf[2] = 0;
  Serial.write(buf, 8);
}

The above code works fine but the problem is that when I tried to play a game, which uses right arrow and left arrow, and to control a car I was using the push button, which I connected to Arduino as left and right arrow keys. But suppose I want to turn a car. I have to press the key and then release the key to move it a very little to the right or left. So, if I want to turn the car either left or right, I have to press and release so many times that it becomes impossible to play the game. Do you anyone know how to resolve this problem?


texts: How to read AC Voltage in arduino uno with 12V adaptor and usb cable.?

texts:
i want to ON-OFF two lights(white and red), one from main power source(white light) and one from ups(battery). When main power is present, white light should be ON and red should be off. And when main power fails, red should be ON and White should be OFF.
I have Arduino, usb cable, external power supplier(adapter of 12V).

Can any one please suggest me how do i proceed for this ??


texts: Source of cheap, small, ~360 rotation sensors (potentiometer, hall effect, etc) for tiny steering wheel like input

texts:
I am trying to make a custom remote control with a knob (kind of like a really tiny steering wheel) that automatically returns to center when input is released (kind of like a joystick).  I only want to control one axis (not two axis like most joysticks).  I want to be able to go either direction from the neutral position (so not like a gas pedal that only goes one way).  Range of motion would ideally be 180 in both directions but 90 may be okay.  I need analog values returned.  I do not want a joystick due to the form factor.
My questions are:

What would this kind of part be called? Spring return potentiometer? Automatic centering hall effect sensor? Center-return analog rocker switch?  I am googling these but getting almost all false hits.
Is there a cheap source of them?  I found some thumb wheels based on hall effect sensors but the cheapest are like $50 each and they may not work because of the range of motion.  I'd think what goes into motorcycle arcade game's throttle control would probably do the trick albeit some may only go in one direction if there is no reverse.

Because of the logistical situation, I don't want to make these from scratch.
Edits:
Can't comment bc I am too new, but by component I mean something I can buy like a joystick.  So I see the comment that a joystick is a pot and springs.  I'd be fine buying the assembly but I am not looking to custom make it from pots and springs.
Also, it doesn't have to be a spring. I just want it to return to center.
I think the wheel on this RC controller may be what I am seeking, but not looking to harvest parts for this production.


texts: Lighting LED Strip via HC-06 Bluetooth Module

texts:
What I Am Working With:
I am working on a project involving an Arduino, some RGB led strip, and my PC.

My Project:
The PC sends UART (serial) data to the Arduino over Bluetooth (through a HC-06 Bluetooth module connected to the Arduino) to change the color of the LED strip. The user could also change "lighting modes" to instruct the Arduino to make the LED blink, fade, etc.

My Problem:
Having no RTOS nor interruptions on data reception, it would be impossible for me to make the LED fade and, also, to receive Bluetooth data to change the lighting mode.

I would appreciate whatever input the community has regarding this problem.

Thanks in advance,
Stanislas.


texts: How can I define integer inputs to a function and get array as an output?

texts:
I am trying to write a function that takes integer values as an input and gives an array as an output. I have tried the following code but it doesn't show the output result in the serial monitor:

int *phi (int cur,int vol,int t) {
  int z[4];
  z[0]=1;
  z[1]=cur;
  z[2]=vol;
  z[3]=t;
//z=cur+vol+t;
  return z;
}

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

}

void loop() {

int result;
result=phi(1,2,5);
Serial.begin(9600);
Serial.print(result);

}


texts:
I'm looking to build a motion sensor which detects if an object is in the monitored area. Doing some researched I found out that I can use PIR motion sensor for this but it seems the area it monitors is pretty small.

I need something that can monitor about 3 feet x 1 feet area. Is there something else that I can use for this?

My goal is to light up some LED lights when an object is detected in that area.

Thanks in advance.


texts:
I have a very specific problem, exactly with real time control. For example I try to write an application where I can edit min or max temperature that after reaching it , I will receive SMS with message. I'm wondering how to edit variables "on-the-fly" because, as I know Arduino IDE use it own libraries not this from C/C++, and I don't know how to get to SD card in Arduino too. Can someone help ?

Thanks


texts: How to use potentiometer on one Arduino to control servo on another Arduino via WiFi?

texts:
I want to connect a potentiometer on one Arduino (master side) and send the readings to another Arduino (client side) to run a servo motor. The communication between the two Arduinos should be via Wi-Fi using two ESP8266. Based on the changing values of potentiometer, the servo motor should run accordingly.

Is there any reference code? Or, if anybody has done this earlier, please share the link of your code.


texts:
I have come across several examples about serialEvent() function, which look like this:

void serialEvent(){
  if(Serial.available()){
    \\do something
  }
}

The serialEvent() function is called when data is available, so which is the necessity of the if (or while) structure since that would be always true?

(In several cases I have excluded the if structure, and the code works fine)


texts: Arduino, lcd 16x2 and UTP cable shows gibberish text?

texts:
I'm using an arduino uno, and an 16x2 LCD that is connected to the arduino uno with a 1m long UTP cable to transmit data and as well power the LCD screen.

I used to test my code and my wiring with short wires and everything worked perfectly, as soon as I used the UTP cable to move my lcd a bit away from the arduino, the same code and wiring doesn't work, all i see is gibberish text (nonsense characters on the screen).
I have other components in the circuit, but I have disabled them all and checked again (quadruplechecked) everything, including the LCD alone, but the problem remians. I also gave the lcd a whole separate powering line, as I thought it could have run low in energy bcs of other components using the same 5v line.

Anyone has any idea of what could the problem be? Has anyone tried connecting components with UTP cables? Should I maybe use STP instead?

Thanks!


texts:
I am trying the esp8266 esp-01, and did all it asked on the arduino IDE side, but i am having problems compiling and building the blink example into the board

Using: FT232RL usb-ttl in the 3.3v configuration, two 1.6v (new) batteries to power the esp, and all the conections as indicated here (not using the led though).

when I hit (go) it compiles, but as it transfers both boards blink sincronously and I recive the following errors:

O sketch usa 219.479 bytes (50%) de espaço de armazenamento para programas. O máximo são 434.160 bytes. Variáveis globais usam 31.172 bytes (38%) de memória dinâmica, deixando 50.748 bytes para variáveis locais. O máximo são 81.920 bytes.

error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data warning: espcomm_sync failed error: espcomm_open failed error: espcomm_upload_mem failed

I looks to me as a newbie that its trying to establish a link and failing... what could it be?

the configurations are default, programmer is "AVRISP MKII"


texts: Loop one specific case inside of a switch

texts:
I want to loop one specific case inside of my switch, until the button gets pressed a second time. How can i make this work?

Code:

const int ledrood = 9;
const int ledgroen = 10;
const int ledblauw = 11;
const int buttonPreset = 2;
const int buttonMix = 4;
float sensorWaarde = 0;
int switchtel = 1;

int roodval;
int groenval;
int blauwval;
int buttonState = LOW;

void setup() {
Serial.begin(9600);
pinMode(ledrood, OUTPUT);
pinMode(ledgroen, OUTPUT);
pinMode(ledrood, OUTPUT);
pinMode(sensorWaarde, INPUT);
pinMode(buttonPreset, INPUT);
pinMode(buttonMix, INPUT);

}

void loop() {
int sensorWaarde = analogRead(A0);
buttonState = digitalRead(buttonMix);
if (buttonState == HIGH) {

delay(200);
switch (switchtel) {
  case 1:
  roodval = 255;
  roodval = sensorWaarde / 4;

    groenval = 0;
    blauwval = 0;
    analogWrite( ledgroen, groenval );
    analogWrite( ledrood, roodval );
    analogWrite( ledblauw, blauwval);
    Serial.println(roodval);
    switchtel = switchtel + 1;
    break;

  case 2:

    roodval = 0; // cyaan
    groenval = 255;
    blauwval = 255;
    analogWrite( ledgroen, groenval );
    analogWrite( ledrood, roodval );
    analogWrite( ledblauw, blauwval);
    Serial.println("2");
    switchtel = switchtel + 1;
    break;

  case 3:

    roodval = 255; // magenta
    groenval = 0;
    blauwval = 255;
    analogWrite( ledgroen, groenval );
    analogWrite( ledrood, roodval );
    analogWrite( ledblauw, blauwval);
    Serial.println("3");
    switchtel = switchtel + 1;
    break;
    switch (switchtel) {

    }
   }
 }
}


texts: Serial Communication Between Two arduinos (Asking and Receiving)

texts:
Can anyone help? I'm trying to develop two sketches, where data can only be sent when a request is made for it between two arduinos. A simple hello world message can suffice. I tried out the Serial Ascii Call and Response on the arduino IDE but it didn't work for me???. Do find below the code sketches

//Arduino Sketch 1
uint16_t alpha;
uint16_t lambo;
Banana nanas;    //to hold the Banana object
uint16_t dataArray[2];
void Setup(){
    Serial.begin(9600);
    establishContact();
}

void loop(){
    alpha=nanas.getRad;
    lambo = nanas.getBars;
    dataArray[0] = alpha;
    dataArray[1] = lambo;
    Serial.write((uint8_t*)dataArray, sizeof(dataArray));
    Serial.flush();   //clear the serial port
}

void establishContact()
{
    if (Serial.available())
    {
        while (Serial.available()  > 0)
        {
            int newByte = Serial.read();
            if (newByte == 'Q')
            {
                Serial.write(newByte);
                Serial.flush();
            }
        }
    }
}

The sketch for the other arduino is shown below

//Arduino sketch 2
static char buffer[2];
void setup(){
    Serial.begin(9600);
    Serial1.begin(9600);
    establishContact();
}
void loop(){
    if(Serial1.available())
    {
        while(Serial1.available() > 0){
            uint16_t gondola1 = Serial1.read();
            uint16_t gondola2 = Serial1.read();
            uint16_t crixus = gondola2 >> 8;
            crixus = (crixus | gondola1);

            gondola1 = Serial1.read();
            gondola2 = Serial1.read();
            uint16_t mario = gondola2 >> 8;
            mario = (mario | gondola1);
            buffer[0] = crixus;
            buffer[1] = mario;
            Serial.write(buffer, sizeof(buffer);
            Serial1.flush();
        }
    }
}
void establishContact(){
    if (Serial.available()){
        uint16_t newByte = Serial.read();
        if(newByte == 'Q')
        {
            Serial.flush();
            Serial.write(newByte);
        }
    }
}


texts:
Going through the "timeouts" example of the elapsedMillis library (https://github.com/pfeerick/elapsedMillis) I found the following statement:

digitalWrite(LEDPIN, flashPattern[ledIndex++] ? ledBrightness : !ledBrightness);

flashpattern is an array of boolean variables  (boolean flashPattern[] = { 1,1,1,1,1,1,1,0,1,1,0 };)
ledBrightness is a boolean as well.

What does the "?" and the ":" do there? are these boolean operators?


texts: I am using the visual micro extension for Visual Studio 2015.  I would like to not use any .ino files since I'm trying to setup cppcheck which doesn't recogonize .cpp files, and its just what I'm used to.  However when I change my project.ino file to project.cpp the compile option is no longer available (I assume its looking for a .ino file).  Is there a project setting I can change to fix this?


texts: Is there a transmission protocol library for SPI?

texts: When communicating over SPI, one byte is sent at a time. Is there a library (C or C++) that allows for sending strings? Essentially it would be a protocol library handling the start and the end of a message, as well as integrity checking. (I'm using an Arduino.)


texts:
I have an Arduino NANO clone and a 2.4" ILI9341 TFT display.  The VCC and LCD pins of the display are connected to the 5V pin of the board.  The GND to the GND.  All the logic pins are connected to voltage dividers (2k2 and 4k3 resistors), their connections checked and delivering 3.3V when 5V is supplied to them.

If I understand the source correctly, if I specify all the pins to the constructor, then I use software SPI, but if I don't, then I use hardware SPI.

Now, if I use the software SPI, everything is working fine, I can get the info, I can draw, etc.  However if I use the hardware SPI then it is not giving me anything.

#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>

// Adafruit_ILI9341 tft = Adafruit_ILI9341(10, 9);              // NOT WORKING!
Adafruit_ILI9341 tft = Adafruit_ILI9341(10, 9, 11, 13, 8, 12);  // WORKING!

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

    Serial.println("ILI9341 Test!");

    tft.begin();

    // read diagnostics (optional but can help debug problems)
    uint8_t x = tft.readcommand8(ILI9341_RDMODE);
    Serial.print("Display Power Mode: 0x"); Serial.println(x, HEX);
    x = tft.readcommand8(ILI9341_RDMADCTL);
    Serial.print("MADCTL Mode: 0x"); Serial.println(x, HEX);
    x = tft.readcommand8(ILI9341_RDPIXFMT);
    Serial.print("Pixel Format: 0x"); Serial.println(x, HEX);
    x = tft.readcommand8(ILI9341_RDIMGFMT);
    Serial.print("Image Format: 0x"); Serial.println(x, HEX);
    x = tft.readcommand8(ILI9341_RDSELFDIAG);
    Serial.print("Self Diagnostic: 0x"); Serial.println(x, HEX);
}

void
loop()
{
    // pass
}

However, what really makes me totally confused is when I use the SD card reader with the SD Library alone (the SD card reader is on the ILI9341 board), then that is working fine as well (as if the hardware SPI would be working, unless the SD Library is switching to software SPI magically).  Anyway, the following is the working code:

#include <SD.h>
#include <SPI.h>

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

    Serial.println("ILI9341 Test!");

    if (!SD.begin(7))
    {
        Serial.println("Cannot initialise SD card");
        while (true);
    }

    File file;

    if ((file = SD.open("file.txt", FILE_WRITE)))
    {
        Serial.print("Writing to file...");
        file.println("Hello, World!");
        file.close();
        Serial.println(" DONE");
    }
    else
        Serial.println("Cannot open file for writing");

    if ((file = SD.open("file.txt")))
    {
        Serial.println("Opening file...");
        while (file.available())
            Serial.write(file.read());
        file.close();
        Serial.println("DONE");
    }
    else
        Serial.println("Cannot open file for reading");
}

void
loop()
{
    // pass
}

So what exactly is going on here?  Am I doing something obviously wrong?  Or is the board's hardware SPI not working?  Or is there a problem with the Adafruit library?

Extra info:

I'm using the arduino-cli to upload sketches the following ways:

# To compile:
arduino-cli                                     \
    compile                                     \
    --fqbn arduino:avr:nano:cpu=atmega328old    \
    --warnings all                              \
    MyArduinoSketch;

# To upload
sudo arduino-cli                                \
     upload                                     \
     --verify                                   \
     --verbose                                  \
     --port /dev/ttyUSB0                        \
     --fqbn arduino:avr:nano:cpu=atmega328old   \
     MyArduinoSketch;

I installed the mentioned libraries via arduino-cli.


texts:
I am trying to connect ESP32 via bluetooth classic to my PC to transfer some data from a sensor.
As a first step, I am simply trying to send some random data over bluetooth serial. The code is at follows:
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

int myData[8];
BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  Serial.println("Opening Serial Connection on COM4");
  SerialBT.begin("ESP32"); //Bluetooth device name
  SerialBT.println("Opening Serial Bluetooth Connection on COM6");

}

void loop() {

  for(int i = 0; i < 8; i++)
  {
    myData[i] = random(0,500);
  }
  if(Serial.available())
    {

     for(int i = 0; i < 8; i++)
  {
    SerialBT.write(myData[i]);
  }

    }
    delay(20);
}

In Windows bluetooth settings, I have paired the ESP32 with windows and connected it. I have set up incoming and outgoing COM ports for bluetooth where incoming port is  COM6 and outgoing port is COM5.
However, when I open arduino serial monitor for COM6, it is empty and no data is being printed. I am using arduino IDE. Furthermore, on COM4, there is nothing printed despite the Serial.println("Opening Serial Connection on COM4"); command which I think should work regardless of bluetooth.
I have tried everything I can think of. I would be grateful if anyone can help me solve this problem as I have been stuck for days


texts:
If the intent is to drive the two LED's with 200-400mA (using PWM @ 38Hz), is there anything wrong with this solution?

Perhaps this is a better solution, as it ensures the current is exactly the same for the two LED's (so that they are not out of phase with each other):


texts:
I had an idea to hack a wireless doorbell so it could send notifications to my phone when someone rings the doorbell.

I pulled out the PCB from the doorbell and powered it using the +5v from the Arduino - so far so good

I used the (once was a wire to the speaker) as an analog input

The issue I have is that the voltage for the chime continues for a long time. eg its at 0 before push then it fluctuates for a second, then returns to 519 for a while, before eventually returning to 0.

Is there a smarter way to do this - I have included my code below.

void loop()
{
  //detect a changing voltage
  val = analogRead(sensorPin); //pin A0
  delay(500);
  oldVal = analogRead(sensorPin);//pin A0

//if the voltage changed then +1 to the ring counter
  if (val != oldVal) {
      ringCounter = ringCounter+1;
  }

  if (ringCounter > 3 && pinDevid1State == false) // someone pressed the doorbell
  {
    if(DEBUG){Serial.println("pinDevid1 is HIGH");}
    pinDevid1State = true;
    Serial.println("DingDong");
    digitalWrite(ledPin, HIGH);
    delay(5000);
    Serial.println("Notification Sent.");

    //reset vars
    val = 0;
    oldVal = 0;
    ringCounter =0;
  }

  if (ringCounter < 3 && pinDevid1State == true) // the doorbell stopped ringing
  {
    if(DEBUG){Serial.println("pinDevid1 is LOW");}
    pinDevid1State = false;
    digitalWrite(ledPin, LOW);
    Serial.println("DingDongEnd");
    //Sending request to PushingBox when the pin is LOW
    //sendToPushingBox(DEVID1);    //Here you can run an other scenario by creating a DEVID2 variable

    //reset vars
    val = 0;
    oldVal = 0;
    ringCounter =0;

  }


texts: Can I specify that analog pins be used for digital output?

texts:
http://arduino.cc/en/Reference/pinMode notes that

  The analog input pins can be used as digital pins, referred to as A0, A1, etc.

Is it possible to configure these pins as digital output pins as well?


texts: Reading a 10-byte buffer out of a PROGMEM string stored in a string table

texts:
I'm storing a large snippet of text in three separate PROGMEM char arrays:

const char script1[] PROGMEM = "....";
const char script2[] PROGMEM = "....";
const char script3[] PROGMEM = "....";

The first two are 32766 characters, and the last one is 23867 characters (the whole string is 89400 characters in total). I store these in PROGMEM on an Arduino Mega 2560 (which then uses about 90K of 256K of available program memory).

I stored these three strings in a table, together with their lengths:

const int TABLE_SIZE = 3;
const char * const scriptTable[] PROGMEM =
{
  script1,
  script2,
  script3
};

const int scriptLengths[] {32767, 32767, 23867};

I have some issues trying to chunk up the string into 10-byte buffers, and processng it that way. I want to iterate through the table, process the first part in 10-byte chunks first, then move on to the second part, and finally the last part.

For a single string (code), the following works fine:

const char code[] PROGMEM = "....";

// Chunk up large code string in PROGMEM.
const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
char workingSpace[CHUNKSIZE + 1];
int baseIndex = 0;

while (baseIndex < sizeof(code)) {
    int chunk;
    if (baseIndex + CHUNKSIZE > sizeof(code)) {
        chunk = sizeof(code) - baseIndex;
        }
        else {
          chunk = CHUNKSIZE;
        }
        memcpy_PF(workingSpace, ((uint_farptr_t)code) + baseIndex, chunk);
        workingSpace[chunk] = '\0';

        // for debugging
        Serial.print("#");
        Serial.print(baseIndex);
        Serial.print("– Got a chunk [");
        Serial.print(workingSpace);
        Serial.println("]");

        baseIndex += CHUNKSIZE;

However, I'm having some difficulties doing the memcpy_PF call using the table.

int tableIndex = 0;
// for each of the three script strings
for (tableIndex = 0; tableIndex < TABLE_SIZE; tableIndex++) {
    // Chunk up large script strings in PROGMEM.
    const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
    char workingSpace[CHUNKSIZE + 1];
    int baseIndex = 0;

    // we can only use sizeof if it's a static var.
    // strlen should only be calculated once, expensive operation (loop until we encounter '\0').
    // now stored statically in scriptLengths table.
    Serial.println("tableIndex: ");
    Serial.println(tableIndex);
    int strLength = scriptLengths[tableIndex];
    Serial.print("length script string: ");
    Serial.println(strLength);

    while (baseIndex < strLength) {
        int chunk;
        if (baseIndex + CHUNKSIZE > strLength) {
          chunk = strLength - baseIndex;
        }
        else {
          chunk = CHUNKSIZE;
        }
        // do memcpy_PF call here

I have tried several options here, mostly having difficulties with the second parameter (how to address the string stored in the table, and increase its indexing parameter). I read that the way to get a string out of a string table is to use pgm_read_word. However, with both of these below, I either get gibberish in the buffer string, or it seems to start in an incorrect location in the string.

memcpy_PF(workingSpace, ((uint_farptr_t) &scriptTable[tableIndex][baseIndex]), chunk);
memcpy_PF(workingSpace, ((uint_farptr_t) (char*)pgm_read_word(&(scriptTable[tableIndex])) + baseIndex), chunk);

Any help would be greatly appreciated!

Thanks!


texts: a program that makes average with the values u acquired from potentiometer

texts:
Schematic: 1 Button and 1 Potentiometer Sketch: Each time the button is pressed, acquire the value of the potentiometer in a array  of 10 positions and print it on the serial monitor or LCD display. at the end print the average (sum of values / 10)
can u help me to do the start?
Its in C
basically u press button 10 times and it acquires 10 numbers of potentiometer once he did that he need to calculate the average and print it  on lcd display or serial monitor


texts:
I am trying to get Arduino working with Protothreads and wanted to confirm I have the basic setup correct. If I have understood the API correctly, then the following code should be what I need to start 2 concurrent threads from inside an Arduino program:

#include <pt.h>

static struct pt t1, t2;

void setup() {
    PT_INIT(&t1);
    PT_INIT(&t2);
}

void loop() {
    doSomething(&t1, 500);
    doSomethingElse(&t2, 500);
}

static int doSomething(struct pt *pt, int interval) {
    PT_BEGIN(pt);
    sleep(100);
    PT_END(pt);
}

static int doSomethingElse(struct pt *pt, int interval) {
    PT_BEGIN(pt);
    sleep(250);
    PT_END(pt);
}

Does anyone see anything that jumps out at them as missing or wrong?


texts:
I have a NodeMCU ESP8266  ESP-12E and I tried uploading a file thru the SPIFFS.  I am not sure why I see OTA instead of the SPIFFS?

Is there a configuration that I missed?


texts: How to remove Arduino Due and Mega shields without bending pins?

texts:
What's your suggested technique for reliably removing Arduino Due and Mega shields while minimizing the chance of bending the strip header pins?
For example, there's a similar discussion here where the asker ended up building a jig to keep everything parallel, but the main PCB was screwed down into the jig (a disadvantage). There is a heap of PCB Pullers/Extractors on the web, but they all seem to relate to edge connected cards.
I'm hoping for multiple answers / techniques. Interested to hear how you do it, or for you to upvote an answer you like. Maybe everybody is just doing the best they can with finger wriggling and manual pin straightening?


texts: Where to connect BLK and GRN pins of Openlog board on my Uno?

texts: I have the following SD card reader on the left side from Sparkfun. In the tutorial they have it connected directly into an Arduino Mini, which has BLK and GRN pins> I would like to connect it to an Arduino UNO. Where do I connect these pins or can I ignore them? Thanks for your help.


texts: Using ATiny102 as HID device(emulating mouse)

texts: I am trying to make my own mouse/keyboard from an attiny (it doesn't have to be attiny102 as the title suggests). I have read many articles on this subject: some are using v-usb library.But I understand this is for arduino uno/leonardo.I want to use an attiny with the least amount of electronic parts attached to it(no external oscillator-only the internal one..etc.). All the articles I read said that arduino can't be used as a host usb device but this applies only for it's built-in micro-usb. Can't I just emulate the HID device using digital pins on my attiny? If this is possible where can you provide some well-documented source for the protocol used when communicating with the pc?


texts:
I'm building a smart shopping cart with Arduino for my final year project.

The cart is supposed to be able to follow its user while shopping. I don't know of many feasible indoor positioning systems to use.

Proposed solution 1

I have recently seen some RF/ultrasonic positioning systems that make use of:

one ultrasound transmitter and one RF receiver, carried by the person,
and two ultrasound receivers and one RF transmitter carried by the robot.

The robots RF transmitter sends out a signal, which when received by the person's RF receiver, triggers the person's ultrasound transmitter to transmit a signal. This signal is received by the robot's two ultrasound receivers (with a distance, d between them), and the distance and angle to the target person can be calculated.

That sounds very feasible, but my question is, if the robot is in a crowded place, where the other people are also carrying ultrasound transmitters and RF receivers:

Will the RF signal meant for the owner of the robot be accidentally received by the RF receiver on another person, or is there some kind of unique ID shared between RF receiver/transmitter pairs that could prevent this problem, or maybe some kind of frequency hopping system, so there would be no mistaken identity.
How will the ultrasound receivers on the robot be sure that the received signal is from its matching ultrasound transmitter. Again, is there some kind of special ID systems employed by some ultrasonic transmitter/receivers.

Proposed solution 2

I have also read about this new device called Trackr, it makes use of bluetooth low energy to track objects based on their proximity to bluetooth enabled devices like smart phones.

Considering a scenario where various bluetooth devices (beacons) are placed at specific points in a room, and the target to be tracked is equipped with a bluetooth emitter/bluetooth chip/dongle.

When the target passes each of those beacons, the signal strength intensity is received and distance from the target is calculated.

I understand this concept, but have some questions:

When distance is calculated between beacon and target, what about the angle, how would the robot follow the target based on distance alone?
If this method is not accurate enough to be used in a crowded space, what other method can be used, I have checked out some indoor GPS devices and they are way to expensive (above $200).

Would a camera-based tracking system be better and how easy would it be for a non expert like me to implement.


texts: How much current needed to power arduino uno?

texts:
I am planning to build an rc car based on arduino uno. I will use 3S 11.1 V Li-po to power whole circuitry. So my question is;

First, can arduino be powered directly with 11.1V from its Vin pin? Would it be a problem or not? If it is OK, then no need to answer the bold part below.

If it is not, then one solution comes to my mind is to use a voltage regulator which will convert 11.1 V to 5 V. But while choosing a regulator, I saw that max output current is one of the important specs. So what is the minimum amount of current needed to run Arduino UNO?


texts: How do I erase the memory of the Arduino Uno?

texts:
I'm just a tinkerer learning Arduino with my son and I was surprised that when I plugged the USB cord back in to the Arduino the program was still running and I thought to myself, "it's a good thing I didn't just blow anything up."

So, what's the normal way people call it a day with these things?  Do you usually load up the bare-bones do nothing sketch or just unplug everything?


texts:
I'm trying to read to voltage output of module ACS712. Here is my problem: The module outputs a voltage around 2.5V, however, arduino sends the value "1023" to the PC. (Gives a reading of 5V).

Arduino's analogRead function works, however, is slow so I used atmega registers to solve the issue. Which worked... Except only for the module. Here is the relevant part of my code:

Setup:

void setup() {
  ADMUX = 0xC0;
  ADCSRA = 0x8E;           // prescaler = 64
  ADCSRB = 0x40;
  sei();
  bitWrite(ADCSRA, 6, 1);    //This starts single converion.
  Serial.begin(250000);
}

Relevant ISR function:

ISR(ADC_vect) {
  sensorValue = ADCL;        // read adcl first. locks adc bytes.
  sensorValue += ADCH << 8;
  Serial.println((int)sensorValue);
  bitWrite(ADCSRA, 6, 1); // Set high so another conversion starts.
}

Now, this code runs as expected for another adc pin which is located at "A3", or in code:

ADMUX = 0xC3;

However, does not work for:

ADMUX = 0xC0;

Yes, I tried replacing the wires A0 and A3. This time "0xC0" works but "0xC3" doesn't. So my arduino somehow is resistant on reading the module output!

Also, this works on same hardware:

sensorValue = analogRead(A0);
Serial.println((int)sensorValue);

Arduino's analogRead runs as expected on same hardware.

So basically, the hardware seems okay, but there seems to be a problem with my code. I just can't read the modules output voltage and I'm all out of ideas. Can anyone help?


texts:
I'm using this OSC library and TouchOSC to controls some motors.
Right now I'm receiving those two kind of messages:

/u/1       // move motor 1 of default steps
/u/2       // move motor 2 of default steps

/u/1/5     // move motor 1 of 5 steps
/u/3/25    // move motor 1 of 25 steps

and so on.

Right now I have this piece of code:

void loop() {
  OSCMsgReceive();
}

void OSCMsgReceive() {

  OSCMessage msgIN;
  int size;
  if ((size = Udp.parsePacket()) > 0) {
    //Serial.println("incoming message.. ");
    while (size--) {
      byte n = Udp.read();
      msgIN.fill(n);
      Serial.print((char)n);
    }
    Serial.println();
    if (!msgIN.hasError()) {
      msgIN.route("/u", up);
    }
  }
}

void upValueExtraction(char *ca, int &num_motor, int &num_step) {
    String s = String(ca);
    String num_motor_s = "";
    String num_step_s = "-1";
    int n = 0;
    for(int i=0; i<s.length(); i++) {
      char c = s[i];
      if(c=='\\') {
        n++;
      }
      if(n==0) num_motor_s += c;
      if(n==1) num_step_s += c;
    }
    Serial.print("num motor: "); Serial.println(num_motor_s.toInt());
    Serial.print("num step: "); Serial.println(num_step_s.toInt());

    num_motor = num_motor_s.toInt();
    num_step = num_step_s.toInt();
}

void up(OSCMessage &msg, int addrOffset) {
  static boolean flag = false;
  if (!flag) {
    Serial.print("route: up "); Serial.println(addrOffset);

    char ca[200];
    msg.getAddress(ca, addrOffset+1);

    int num_motor, num_step;
    upValueExtraction(ca, num_motor, num_step);

    if(num_step==-1) {
      num_step = defaul_steps;
    }

    Serial.print("Have to move motor n ");
    Serial.print(num_motor);
    Serial.print(" of step ");
    Serial.println(num_step);
  }
  flag = !flag;
}

Even if it is working and even if I'm using an Arduino DUE (much more memory then the UNO) I think it can be optimised.

Does it contains some leeks? How can I better use the OSC matching part of the library? Any kind of "embedded c++" guidelines? Can I do everything inline without a ca char array and s String variables? Is better to use Arduino Lib String class or plain old C str* functions? Any kind of comment?

Thanks in advance.


texts: How to pass JsonObject from ArduinoJson to ESP8266WebServer object?

texts:
I am learning the ArduinoJson.h library and creating jsonOject:

JsonObject& prepareResponse(JsonBuffer& jsonBuffer) {
  JsonObject& root = jsonBuffer.createObject();
  JsonArray& tempValues = root.createNestedArray("temperature");
  tempValues.add(t);
  JsonArray& humiValues = root.createNestedArray("humidity");
  humiValues.add(h);
  JsonArray& dewpValues = root.createNestedArray("dewpoint");
  dewpValues.add(pfDew);
  JsonArray& EsPvValues = root.createNestedArray("systemv");
  EsPvValues.add(pfVcc / 1000, 3);
  return root;
}

As per the example given here. However since I am using an ESP8266WebServer to create a server object from ESP8266WebServer.h, I cannot pass a JsonObject to server.send(.....).

  no matching function for call to 'ESP8266WebServer::send(int, const
  char [10], ArduinoJson::JsonObject&)'

void outputJson() {
  StaticJsonBuffer<500> jsonBuffer;
  JsonObject& json = prepareResponse(jsonBuffer);
  writeResponse(client, json);
  server.send ( 200, "text/json", json );
}

void writeResponse(WiFiClient& clnt, JsonObject& json) {
  clnt.println("HTTP/1.1 200 OK");
  clnt.println("Content-Type: application/json");
  clnt.println("Access-Control-Allow-Origin: *");
  clnt.println("Connection: close");
  clnt.println();
  json.prettyPrintTo(clnt);
}


texts:
I'm having a problem with my MPU6050. I'm using PID to speed up a motor with the MPU values. What could the problem be?

Here is a link to a previous question that I asked concerning a problem with pid: PID not working correctly

These are the values that I'm getting, which repeat forever. The values are:

motor speed;
the value that changes the motor speed;
the MPU value;
the change that PID made.

0.00
0
10900
4800

0.00
0
10900
4800

Here is the code itself.

int16_t ax, ay, az;

double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp=2, Ki=5, Kd=1;
PID myPID(&Input, &Output, &Setpoint, Kp,Ki,Kd, DIRECT);

void setup() {
 Input = analogRead(ax);
  Setpoint = 100;
  //turn the PID on
   myPID.SetMode(AUTOMATIC);
}

void loop() {
 accelgyro.getAcceleration(&ax, &ay, &az);
  int a=ax+10900;
//Here I set the used variable to around 0. ax is actually around -10900
//This is always true, this won't be in the final code. This is just making        it work.

if(1) {
 int val;
  val = map(a, -1300, 1300, 0, 1023);
   Input = val;
    myPID.Compute();
     Serial.println(Output);

digitalWrite(motorPin2, HIGH);
Serial.print("\t");
Serial.println(ax);
Serial.print("\t");
Serial.println(a);
Serial.print("\t");
Serial.println(val);
     }
}


texts:
i'm using this serial topology to connect my Act ATmega328p (Arduino) slaves together to a master ESP32.

They are in total 10 ATmega328p slaves and one master:

With this type of wiring i'm sure that only one slave per time will talk back to master (when requested), now here comes the problem, basically i need dynamic addressing of slaves: they can be many (up to 30) and i need to access in order the slave devices.

In order to solve the "dynamic addressing" problem i'm thinking about that:

The first slaves will be plugged in and will send to the master his default address (i.e.: 0xFF)
The master will check if the address is used and then reply back to the device with the first available address (i.e.: 0x01)
The slave will get back the response from the master and set an internal variable with the new address (maybe it's a good idea to store the variable in a EEPROM like M24C02: enter link description here)
Starting from the next cpu cycle, the master will ask sequentially to all enumerated slaves to (for example) do an analog read using this workflow:

The master will send a message to the serial bus with address 0x01 asking to do an analog read
The respective slave will handle the request, read the analog input and then reply back to the master
I think that this can work, but i've not found any kind of this implementation...maybe i'm totally out of mind?

New idea and concept

Guys, what do you think about sequentially power up the circuits and using the same mechanism to assign dynamically the address?

This assumption will avoid me to save the assigned id to the eeprom and some other id software function defined functionalities like address reset, etc...

It can be a good (and dynamic) method to solve the problem, about that, how I can implement this sequential power up?


texts: How do I read the fuse bits from within my sketch?

texts: How can I read the fuse bits from within my sketch?


texts:
I have connected an LCD with an I2C backpack to my Arduino Uno but it prints the wrong characters. The weird thing is that it worked fine for a while and when I updated the code (but didn't change anything to do with the LCD) it started displaying the wrong characters. This happened earlier today too. That time, reinstalling the LiquidCrystal library worked, but it doesn't now.

Does anyone know what might be the problem so I can fix it permanently?

The LCD's SDA and SCL are connected to A4 and A5 respectively and I'm running this code:

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

LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16     chars and 2 line display

void setup()
{
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("Hello, world!");
}

void loop()
{
    }

and this is what's displayed on the screen:


texts: 'OUTPUT' was not declared in this scope - ATtiny85 with Arduino Uno r3 as ISP

texts:
I'm trying to follow this this tutorial to program an ATtiny85 micro-controller using my Arduino Uno r3 as the ISP.

I am up to the final step on the tutorial, but get an error when attempting to compile my sketch:

'OUTPUT' was not declared in this scope

I have tried multiple "Blink" scripts, but none have seemed to work.

My full error log:

Blink.ino:10:21: error: Arduino.h: No such file or directory
Blink.ino: In function 'void setup()':
Blink:15: error: 'OUTPUT' was not declared in this scope
Blink:15: error: 'pinMode' was not declared in this scope
Blink.ino: In function 'void loop()':
Blink:20: error: 'HIGH' was not declared in this scope
Blink:20: error: 'digitalWrite' was not declared in this scope
Blink:21: error: 'delay' was not declared in this scope
Blink:22: error: 'LOW' was not declared in this scope

I have also tried including Arduino.h, no help, and changing "OUTPUT" to "0x01", as it is defined to said value in Arduino.h, but instead got this error:

error: 'pinMode' was not declared in this scope

Any ideas as to what is happening?


texts: op amp circuit single sourced from arduino power

texts:
Getting an audio signal from a 3.5mm jack amplified (non-inverted) and fed into analog in pin on a Mega 2560. I am having problems using a potentiometer as a variable resistor to adjust gain. I'm also getting a lot of noise (+/-10 units on the 0-1023 scale)

Circuit:
- The audio is from a mono 3.5mm jack, playing from my laptop (with audio split to my speakers).
- Audio goes through an op amp TL071, single sourced shared with arduino 5V
- The potentiometer is wired with 2 pins as a variable resistor. The pins are connected to ground and the inverting input (VCC-)
- Output signal from the op-amp is biased by 2.5V and seems to work fine.

I'm closely following the instructions here (https://www.instructables.com/id/Arduino-Audio-Input/) but with a TL071 op amp as a single sourced from the Arduino 5V power supply.

The potentiometer doesn't seem to make much difference; I can even unplug it and I still get some readings on A0. I'm misunderstanding how to 'rewire' the op-amp for a single supply, but I can't figure out what else I can do.


texts:
I'm starting a decently sized project around arduino/ATMELavr, and I came to wonder if there are any commonly accepted C/C++ coding standards or style guidelines specifically aimed at embedded C++/arduino.

I've worked mostly with python recently, and came to love the PEP8 guidelines, and the associated pep tool (which checks syntax consistency with the style guide).
Similarly, I've used jslint and similar tools for javascript, as I find they help keeping your code base homogeneous, and avoid wasting time and commits on silly typos, and arguing over where the braces should go.

Any similar tools for C++ or more specifically arduino C++?


texts: Arduino NRF24L01+ arduino to netmf transmit issue

texts:
I want to communicate between Arduino Mini Pro (china import) and a stm32f4 running netmf runtime. At the moment I'm able to communicate between SPI1 and SPI2 on the stm32 board.

After that I switched on the Arduino. I'm using the RF24 library and modified the GettingStarted sample to simply open pipes and send the same byte array again and again to the stm32.

It works for the first transmit but after that I did not receive any interrupts on the receiver side.

Both NRF24L01+ are power supplied by a breadboard power supply module which supplies 500ma (max USB bus). The Arduino is connected and power supplied by a CP2102 USB/Serial adapter.

NETMF Address: 0F0F0F0F0F
Arduino Address: 0F0F0F0F0E

As arduino uses little endian, I reverse the bytes on stm32 side before writing the address into the pipe. But I'm already unsure if I need that step (adding the Arduino address on netmf side).

Here's my Arduino code:

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"

RF24 radio(9,10);

const int payload_size = 4;
const char payload[] = "PING";

void setup(void)
{

    Serial.begin(57600);
    printf_begin();
    radio.begin();
    radio.enableDynamicPayloads();
    radio.setChannel(77);
    radio.setAutoAck(true);
    radio.setRetries(15,15);
    radio.setDataRate(RF24_2MBPS);
    radio.openWritingPipe((uint64_t)0x0F0F0F0F0FLL);
    radio.openReadingPipe(1,(uint64_t)0x0F0F0F0F0ELL);
    radio.stopListening();
    radio.printDetails();
}

void loop(void)
{
    unsigned long time = millis();
    bool ok = radio.write( payload, payload_size );

    if (ok)
        printf("SUCCESS %lu...\n",time);
    else
        printf("fail %lu...\n",time);

    // Try again 1s later
    delay(1000);

}

Here's my NETmf code

NRF24L01Plus _module = new NRF24L01Plus();

public override void Init()
{
    _module.Initialize(SPI_Devices.SPI2, Pins.GPIO_PIN_D_8, Pins.GPIO_PIN_D_10, Pins.GPIO_PIN_B_12);
    _module.Configure(new byte[] { 0x0F, 0x0F, 0x0F, 0x0F, 0x0F }, 77, NRFDataRate.DR2Mbps);

    // both handlers are never executed
    _module.OnDataReceived += this.OnReceive;
    _module.OnInterrupt += _module2_OnInterrupt;

    _module.Enable();

}


texts: Attiny45 resets when setting digitalOutput to low

texts:
I currently try to program an Attiny45 with an Arduino UNO as ISP.

The Arduino is able to program the Attiny45.

However, when I try the blink example, it resets the Attiny, when setting digitalOutput to low
(on any pin)

To further confirm, that it resets only, when setting a pin to low, I wrote this sketch and let it run on the Attiny.

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

void loop() {
  delay(1000);
  digitalWrite(3, HIGH);
  delay(1000);
  digitalWrite(3, LOW);
  delay(10000);
  digitalWrite(3, HIGH);
  delay(1000);
  digitalWrite(3, LOW);
}

The LED I connected to pin 3 waits 1 second, and then turns on, but when 1 second passed and it should stay off for 10 seconds, it resets and only waits 1 second.

I tried reburning the bootloader onto the Attiny, which had no effect.


texts:
I'm working on an Arduino project involving an UNO.
I'm powering a 20x4 LCD screen and I am using all the ports on the Arduino, to the last.

All but four of them are pulled high at any given time, so by the time I'm done with pulling them all up the screen is going dim when powering via USB.
So I tried powering via an external 9V 600mA adapter, but that makes the Arduino overheat and eventually shut down.
I then tried another, 12V 500mA adapter, and that one doesn't even get my UNO to the end of the setup function, and it reboots repeatedly.

Anyone got good advice? Ideas?


texts: Arduino LCD Display 2x16 custom char byte limit

texts:
Some years ago I stumble with a problem while using the 2x16 LCD. What happened was that there was a limit to how may byte arrays I could declare. So my project came to a halt because I needed to create more custom characters to advance any further...

The lcd accept custom characters to store them but I suppose there is a limit to this, am I wrong?

I'm trying to create a set of custom characters that move on screen. Since there are a lot of animations I need several of them to have a smooth animation. The problem resides in the limit of characters I can pre-establish after executing lcd.begin()

I don't post code because to my understanding that is not relevant and because sincerely is a crap since I wrote it down when I was learning programming some years ago. I want to resolve this so I can rewrite the code.

LCD version: QAPASS 1602A

Here is an example:

byte Ghost[8] = {
  0b00000,
  0b01110,
  0b01110,
  0b10101,
  0b11111,
  0b11111,
  0b11111,
  0b10101
};

lcd.createChar(0, Ghost);

So the right question is: Do I need to reset the LCD chip then declare the new characters to the lcd to make it available? How?


texts: I2C Master-Slave Arduino system to control array of steppers

texts:
trying to make a system where one master Arduino makes moving 9 steppers 28BYJ-48 by 3 stepper on each slave arduino.
While all the parts on their way to me, wonder to check with professionals.
Maybe I've missed something?
Any suggestions and tips are welcome.
Thank you.


texts: Creating public instance of class in another class's initialization

texts:
I'm using several TM1637 displays to create timers, so I decided to make a Timer class. Every time I initialize an instance of the Timer class, I want it to create an instance of the TM1637Display class. So I started out with this, but the display object can't be accessed from within updateDisplay.

class Timer {
public:
    Timer(uint8_t CLK, uint8_t DIO) {
        TM1637Display display(CLK, DIO);
        ...
    }
    void updateDisplay() {
        ...
        display.setSegments(displayData);
    }
}

And if I do this I get the compile time error In constructor 'Timer::Timer(uint8_t, uint8_t)': src\main.cpp:16:37: error: no matching function for call to 'TM1637Display::TM1637Display()'

    TM1637Display display;
    Timer(uint8_t CLK, uint8_t DIO) {
        display(CLK, DIO);
        ...
    }

What should I try? Maybe make an empty pointer before the display instance is created with a public scope, assign the pointer to the display instance, then hand the updateDisplay function the pointer? That seems really convoluted.


texts: How to detect the pulse width from microphone as Input?

texts:
I'm working on a project that detects the pulse width of an audio signal, which uses a microphone as an input. The user gives 2 different types of sounds one last less 0.3 seconds and other lasting less than 0.7 seconds. I've attached the audio visualisation of the signal pic in the attachment.
All want to detect is their pulse widths.

I tried Pulsein() - but as you can see that it has a variable until 0.3 or 0.7 seconds it only detect the first and most peak and returns the value which is almost zero.

But all I need is the total time taken for the pulse to rise from 0 and to variate and then become 0 this total time period is what I require.
would duty cycle help ? or any other functions available to detect two different sounds in arduino ?

pulse width


texts:
I want to include a function in my sketch I moved to a .h file.
I did it as follows:
My code:
#include "header.h"

void setup() {
  fct();
}

void loop() {

}

My header:
#include "Arduino.h"
#ifndef MYHELPERS_H
#define MYHELPERS_H

void fct() {
// stuff
}

#endif

The same process seems to work for variables but the IDE says this function in not declared in this scope...
I don't understand what I'm doing wrong...
Thanks guys!


texts: I have three pushbuttons where only one can be pushed at a time and want to set a variable for this. How?

texts:
Basically I have three push buttons that correspond to pins 1 to 3 and want to set an efficient code that sets a certain variable into the index whose digitalRead is equal to one. Let us assume that only one button can be pressed at a time.
void loop()
    {
    if(digitalRead(1) == 1)
        {
        Variable = 1;
        }
    if(digitalRead(2) == 1)
        {
        Variable = 2;
        }
    if(digitalRead(3) == 1)
        {
        Variable = 3;
        }
    }

Is there are more efficient way to do this, like for example using other loops?
I can't wrap around my head with doing this concept using the other loops such as for, do while, while and switch because the nature of the idea feels so unconventional for their uses.


texts:
I have a system that involves an Arduino Due connected to a Raspi 4 through UART in which the Due sends a heartbeat signal over UART for the pi to receive and send back as confirmation. One of the events that I need to handle is re-establishing the UART connection between the two devices if the program receiving UART on the pi (or the pi itself) fails for any reason and reboots. At the moment, I have the initial heartbeat working (as long as the pi program starts first) but when I stop the pi program to simulate a fatal error and restart it, the Due doesn't seem to receive heartbeat confirmation until it's reset as well.
Is there a clean way to reset just the one Serial connection from the Arduino script? I thought of using Serial.end() and Serial.begin() but that's really ugly and I'd prefer to avoid it. None of the other Serial library methods seem to provide the ability to reset the connection.
I'm using Serial2 at 115200 baud.
Edit: Including relevant heartbeat code:
#include <DueTimer.h>

bool heartbeat = true;

void rx_heartbeat() {
  int received_data;

  if (Serial2.available() > 0) {
    received_data = Serial2.read();
    heartbeat = true;
    Serial.println("beat");
  }
}

void setup() {
  Serial2.begin(115200);
  Timer1.attachInterrupt(heartbeat_ISR).setFrequency(1).start();
}

void loop() {
  rx_heartbeat();
}

void heartbeat_ISR() {
  if (heartbeat) {
    heartbeat = false;
  } else {
    // no heartbeat returned - stop normal operation
  }
  Serial.println("heart");
  Serial2.write(255);
}


texts: how to fix mirrored text on 3.2 inch IPS TFT LCD Display ILI9481 480X320 36 Pins for Arduino Mega2560

texts: i am working on a project on my arduino mega2560. I want to show reading of the sensors on the TFT display, the problem is the text displayed on the screen is mirrored. Since i am very new to arduino i don't know how to fix the problem. I have check a few videos on youtube but nothing helped. I am using the example from the UTFT library arduino (AVR) => UTFT_DEMO_480x320


texts: if/else statements without comparison operators and curly braces

texts:
I recently came across this code in a tutorial. The code works, but this form of syntax seems to differ quite a bit from https://www.arduino.cc/reference/en/language/structure/control-structure/if/, as it's lacking comparison operators and curly braces for statements. Can someone please run down why this works?

for (int i = 0; i < 15; i++)
{
lcd.setCursor(i, 1);
if (pressed[i])
  lcd.print("X");
else
  lcd.print(" ");

if (justpressed[i])
  digitalWrite(led, HIGH);
else
  digitalWrite(led, LOW);
 }


texts:
Whenever I upload the following program I am getting error message
showing "expected initializer before interval".

Kindly Help me to solve out this probleme.

const byte button=2;
const byte LED=10;
bool blinking =false;//defines when blinking should occur
unsigned long blink Interval=250;// number of milliseconds for blink
unsigned long currentMillis;// variables to track millis()
unsigned long previousMillis;
void setup()
{
    pinMode(button,INPUT);
    pinMode(LED,OUTPUT);
}
void loop()
{
    // this code  blinks the LED
    if(blinking) {
        currentMillis =millis();// better to store in variable, for less jitter

        if((unsignedlong)(currentMillis-previousMillis) >=blinkInterval) { // enough time passed yet?
            digitalWrite(LED,!digitalRead(LED)); // shortcut to toggle the LED
            previousMillis =currentMillis;// sets the time we wait "from"
        }
    } else {
        digitalWrite(LED,LOW); // force LED off when not blinking
    }

    int reading=digitalRead(button);
    delay(50); // crude de-bouncing

    if(reading==LOW) // buttons with pull-up are pressed when LOW
    { blinking =true; }// start blinking
    else
    { blinking =false; }// stop blinking
}


texts: When accessing a variable from an ISR, is a volatile pointer enough?

texts:
Let's say I want to modify a global variable from inside an interrupt service routine. I must ensure that any variables I modify are volatile. Does it work to use a volatile pointer to data I want to modify if the data itself is not volatile?
In my case the data is a struct, but does the answer change if the data is a class, array, or just a variable?
#include <Arduino.h>

#define PIN_INTERRUPT  2

typedef struct MyStruct
{
    int a_field;
} MyStruct;

MyStruct struct_data;
int array_data[32];

volatile bool _flag_ISR = false;
volatile MyStruct *_struct_ISR = &struct_data;
void myISR()
{
    // just some example stuff
    int read = digitalRead(PIN_INTERRUPT);
    _struct_ISR->a_field = read;
    _arr_data_ISR[4] = read;

    _flag_ISR = true;
}

void setup()
{
    attachInterrupt(digitalPinToInterrupt(PIN_INTERRUPT), myISR, CHANGE);
}

void loop()
{
    if (_flag_ISR)
    {
        // do processing here...
        _flag_ISR = false;
    }
}


texts: Stepper motor shield compatibilty question

texts:
I recently bought Adafruit's motor shield v2 only to find out it can only support upto 12v.

So I'm on the look out for another shield & found this one
Arduino Dual L6470 Stepper Motor Shield

I have an Arduino Mega & the documentation says it is fully compatible with the UNO.

Will there an issue using this shield with a Mega? Or if anyone else can point me at a decent stepper controller?


texts: MPU6050 stuck on same values while getting the angle as output

texts:
I am trying get the rotation value from MPU6050. I am using an Arduino Uno board.

My connections are:

MPU6050  Arduino

VCC    ->  5V
GND    ->  GND
SCL    ->  A5
SDA    ->  A4
INT    ->  2

The code I am using is:

#include <MPU6050_tockn.h>

#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup() {

  Serial.begin(9600);

  Wire.begin();

  mpu6050.begin();

  mpu6050.calcGyroOffsets(true);

}

void loop() {

  mpu6050.update();

  Serial.print("angleX : ");

  Serial.print(mpu6050.getAngleX());

  Serial.print("\tangleY : ");

  Serial.print(mpu6050.getAngleY());

  Serial.print("\tangleZ : ");

  Serial.println(mpu6050.getAngleZ());

  delay(4000);

}

On my serial monitor I am always getting -35.26, 35.26, -0.0 values. What should I do?


texts: How to send JSON on a http POST request using an ESP8266?

texts:
I'm working on a project aimed on sending alerts via SMS. I signed up for a SMS service that works via HTTP requests (REST standard). I need, then, to send data as JSON, so that their server processes the data and sends the SMS message to a list of recipients.

I am working with an ESP8266 board. I have tried some code, but I couldn't do the JSON part properly, given I have little knowledge on HTTP requests and HTTP libraries for Arduino. I managed to test things using python code (with which I am much more familiar).

In short, I have this piece of code in python that works quite perfectly:

payload = {'sender': '558499999999','content': 'Just a message', 'groupName': 'Recipients_list'}
request = requests.post('https://cheap.sms.sending.guys/sendcontactmessage',
                         data=json.dumps(payload),
                         headers={'content-type': 'application/json', 'auth-key': 'My_authentication_key'})

I tried to write something that does the same thing on a ESP8266, but it is not working and I can't figure the correct way to do it. The code I tried was the following:

#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "my_ssid";
const char* password = "my_password";

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

  //TESTING JSON CREATION
  Serial.println("Starting JSON");
  StaticJsonBuffer<69> jsonBuffer;
  char json[] = "{\"sender\":\"558499999999\",\"content\":\"Just a message\",\"groupName\":\"Recipients_list\"}";
  JsonObject& root = jsonBuffer.parseObject(json);
  if(!root.success()) {
    Serial.println("parseObject() failed");
  } else {
    Serial.println("JSON OK");
  }

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print("Connecting... ");
  }

  //TESTING POST
  //headers={'content-type': 'application/json', 'auth-key': 'My_authentication_key'}
  String sms_service_URL = "https://cheap.sms.sending.guys/sendcontactmessage";

  Serial.println("TESTING POST");
  //Declare an object of class HTTPClient
  HTTPClient http;

  if (WiFi.status() == WL_CONNECTED) {
    //Specify request destination
    http.begin(sms_service_URL);
    http.addHeader("Content-Type", "application/json");
    http.addHeader("auth-key", "My_authentication_key");

    String data;
    root.printTo(data);
    //Send the request
    int httpCode = http.POST(data);

    //Check the returning code
    if (httpCode > 0) {
      //Get the request response payload
      String payload = http.getString();
      //Print the response payload
      Serial.println(payload);
    }
    //Close connection
    http.end();
    Serial.println(httpCode);
  }
}

void loop() {

}

I am aware that the arduino code is pretty lame. I was just in a trial-failure process, lol.

I'd appreciate any suggestions


texts: How do I install a library in Arduino Yun cross compile environment?

texts:
A few days ago, I've asked this question.
Thanks to the replies I've received, I've set up a cross compile environment for Yun by following this guide.
I've created a virtual machine with virtualbox and installed Debian 8.0 on it. I installed all the software required to download and compile the OpenWRT-Attitude Adjustment version (which, I think, is the version used by Arduino Yun) on Debian.
So, I've downloaded the OpenWRT source code, downloaded its packages feed (with "git clone git://git.openwrt.org/12.09/packages.git"), downloaded and installed all available "feeds" (with: "./scripts/feeds update -a" "./scripts/feeds install -a") and then compiled it with: "make defconfig" "make prereq"
and "make menuconfig".
When I typed in "make menuconfig", a graphical interface prompted. In that interface I selected:
Target System: (Atheros AR7xx/AR9xx);
Base System: I selected libc, libcc and marked as package libpthread and librt.
I left any other option as default. Then I compiled all with "time make V=99" command.
After about 2 hours, the compiling finished and I set the environment variables as the above mentioned guide described.
Looks like now I can compile any C code with this cross-compiler. Anyway, my application includes the png.h header in order to use the libpng library, and every time I try to cross-compile it, a "png.h not found" error pops up during the process.
So I tried to cross-compile the libpng library but when I ran "./configure" with the options for cross-compiling, it failed saying that zlib wasn't installed. So I downloaded the zlib library source code but looks like I can't cross-compile it.
Eventually I compiled zlib and libpng normally on Debian and now, when I try to cross-compile my application, it still says that it can't find png.h...
So, how can I "integrate" the libpng library to the cross-compiling environment?
Sorry for this long question, but it is all I've done today.
As always, I thank you for any help you can give me.


texts:
I want to know is it possible to control an Arduino through a website. I have seen some tutorials that are doing it but it is in a local network.
What i am trying to do is :
- Arduino connected to internet ( wifi/ethernet).
- Website.
- Login to website from anywhere in the world.
- Control the Arduino by sending commands from the website itself.

Thanks for your response.


texts: How to burn the bootloader and upload sketches on ATmega328P U (specifically this model)?

texts: Recently I started to learn embedded electronics and C/C++ and for a couple of days I tried and I am still trying to burn a new ATMega328P U bought from Aliexpress. From what I know new ATMega328P's come with bootloader included, but after I wired everything up and connected the FTDI FT232RL to load the sketch (wiring is completely right after many many hours of checking on the internet for a dozen of pictures), I get errors like "programmer is not responding" in case of sketch upload and "error while burning the bootloader" or "Yikes, signature bla bla". I don't think the FTDI is the problem since the Arduino IDE recognizes it as COM7 on my PC. Now here's my question: is my atmega328p u broken or have I missed something during the process of both (trying to) burn(ing) the bootloader and upload(ing) the blink sketch? (I have also tried uploading the board programmer from Nick Gammon on my arduino Uno and the burning the bootloader AND followed the instructions from arduino.cc "from arduino to microcontroller on a breadboard"). If you need pictures of some sort, I'll provide them


texts: How many pins does this circuit (HMC5883L) use?

texts:
I've been told 2 by a friend but this looks to only use one?

https://www.adafruit.com/product/1746


texts:
I am encountering problems with I2C when trying to attach a 9DoF Sensor to my Arduino Uno. Following these instructions (the hardware setup I have is like in the schematic) I noticed the basic example not working. I've since debugged different aspects and when I use the "I2C Scanner" example from this page it seems something basic with I2C must be wrong. The code from there I am using is:

// I2C Scanner
// Written by Nick Gammon
// Date: 20th April 2011

#include <Wire.h>

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

  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }

  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;

  Wire.begin();
  for (byte i = 8; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1);  // maybe unneeded?
      } // end of good response
  } // end of for loop
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");
}  // end of setup

void loop() {}

Instead of this suggested sample output:

I2C scanner. Scanning ...
Found address: 42 (0x2A)
Done.
Found 1 device(s).

The output I am getting is in Serial monitor on the correct baud rate is:

ù
I2C s

With other examples I have tried I have similar results. As soon as something calls Wire.endTransmission() things start to crash and burn.

Any ideas what this could be or how to debug it?


texts:
I recently bought an Arduino MEGA2560 and a SainSmart InstaBots Robot Controller Shield for Arduino MEGA2560 R3 Robot Arm Control.

I understand how to control a servo in the method described in Sweep. However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?

Please help me I am a beginner in robotics and I need this for a project.


texts: Oscillating Output from Arduino Pins when not in use, why?

texts:
I have A1 set to be an input, have the program read it, and then print to the serial monitor. My question is, when the circuit is not receiving power, but is grounded, and is still connected to A1, when do I see an output pattern of, for example:

0,0,0,0,7,23,16,9,4,0,0,0,0,3,18,21,15,0,0,0.....

I have a different detector inputing to A0 and if I don't have A1 connected then I get a reading that is similar to what I would see if I was actually reading A0 (around 900). Then if I plug back into A1 the value drops to around 350. When A0 is unplugged and only A1 is plugged in I only get noise (ie the pattern above in the code section).


texts: Arduino Uno with UsbSerial Android library w/ baud rate over 9600?

texts:
I am having no issues talking to Android at baud rate of 9600. But once I raise the baud rate to anything higher Android seems to become deaf. When I try to read the Serial output using putty all seems fine.

Has anyone had success with baud rate over 9600 when talking to Android?

I am using the felHR85/UsbSerial library.


texts: How Do I Send An Email WITHOUT An Ethernet or WiFi Shield

texts: I can only find info relating to the wifi shield, but I want to send an email without the wifi shield. For now, I just plan on leaving my arduino plugged into a computer, so I just want to use the computer's network connection. Is there a library or something I can grab for this?


texts:
I followed this guide and evertything works until I'm at chapter Configuring the onboard WiFi.

I can see the arduino as an AP.

And I can connect with it. However when entering the IP adress 192.168.240.1 or arduino.local it does not give me the login page.
When using the IP adress I get: the site is not accessable screen. Using arduino.local gives me a page that loads forever for a long time before giving me the exact same result.

I have looked on different forums for a solution. This one said that I should download bonjour and bonjour browser because they use the same port (port 5353). After installing the bonjour browser I should be seeing a connection called .arduino._tcp but I don't see that. In fact I often can't see any connection what so ever.

and sometimes I can see a few connections but none of those are the arduino.

I have tried to ping with the arduino on the adress 192.168.240.1 but all I got was a time out.

Pinging 192.168.240.1 with 32 bytes of data:
Request timed out.

Edit : I managed to get the bonjour browser to work all the time, by installing itunes. It also shows the arduino.


texts: I need to produce a log to base 10 with at least 4 decimal places. However, the log10 inbuilt function is giving the output with only two decimal places. What do I do? Is there a different function or a library that I can use?


texts:
I'm remotely connecting my phone to an arduino MKR1000 via wifi, and sending data via HTTP GET (so to switch on the debug LED, I just need to navigate to http://192.168.1.1/debug/H, for example). Now, I want to be able to remotely send animations to an RGBW led strip.

Ideally, I would have a simple keyframe based protocol such as:
    http://192.168.1.1/anim/(keytime in ms):R,G,B,W+(keytimeinms) etc...

So for example, to animate from white to red in 500ms, I would navigate to:
    http://192.168.1.1/anim/0:255,255,255,255+500:255,0,0,0

Is this the best way to remotely send animations to my arduino? How should I implement this on the arduino side in the most ressource-efficient way possible? I don't even know where to start :/
For the moment, on the arduino side, I've got a keyframe class and an array of those keyframes representing the animation.


texts: Copy outbound data of Serial to Serial1 for Pro Micro

texts:
I am working on a bluetooth HID device. There are libraries which make HID devices a cake walk if you are making a wired version of your HID device.
I managed to configure my bluetooth module to appear as a HID device to the system, it however does nothing yet.
I figured if I route the serial data, that my wired version of device is sending to the system on Serial, to Serial1 my bluetooth device will function the same way the wired device worked.
If I am not wrong, code that I came across, maps RX of Serial to TX of Serial1.
Void setup(){
    Serial.begin(9600);
    Serial1.begin(9600);
}
void loop(){
     if(Serial.available()){
      char get= Serial.read();
      Serial1.Write(get);
     }
}

What I want to do is map the TX pin of Serial to TX pin of Serial1 of the pro micro.


texts: Change Options for the AVR Programmer via Arduino IDE

texts:
I want to program an ATtiny through the Arduino IDE. I have a somehow strange programmer. But I can upload via avrdude by

  avrdude -p attiny13 -P /dev/cu.usbmodemfa131     -c stk500v2    -F -B20 -U flash:w:programm.hex

It took a while to figure out that I had to slow the baud rate via the -B20 switch. If I try to upload via the arduino 1.0.5 IDE avrdude is executed as follows.

  /Applications/Adafruit Arduino 1.0.5.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -C/Applications/Adafruit Arduino 1.0.5.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -pattiny13 -cstk500v1 -P/dev/tty.usbmodemfa131 -Uflash:w:/var/folders/9t/5jldfq752fs1x74_rhn2plz80000gn/T/build7680201613426497544.tmp/attinytest.cpp.hex:i

My question is, how can I change the preferences such that I have control over the avrdude parameters? Say I want to add a -B20 switch and change stk500v1 to stk500v2.


texts:
I need to communicate with an Arduino. When I use serial.readline() to read what Arduino has to say it works fine. But when I useserial.write('something') doesn't seem to do anything.

Interesting thing is that if I write the same code in the console or command-line, it works as expected...

Using Python 2.7.

Python code:

import serial
import time

arduinoSerialData = serial.Serial('com6', 9600)
time.sleep(1)

while True:
    arduinoSerialData.write('AAA')
    arduinoSerialData.flush()
    sleep(0.5)

Arduino code:

void loop() {

if (Serial.readString().startsWith("AAA")) {
    digitalWrite(7, LOW);
} else {
    digitalWrite(7, HIGH);
}

delay(500);

Again, Python code runs fine from the console, so no idea why this happens.


texts: Trying to get pseudorange data out of NS-RAW GPS

texts: I have an NS-RAW CPGPS and I am trying to get GPS Data using an arduino. Do I just use the serial to get the data out of it and just convert and extract the data to what I need?


texts: 12V dc fan motor rpm finding using tacho out

texts:
I need an Arduino program to find the RPM of a 12V DC fan motor.

I don't want to control the speed. I only want to find the speed of the motor using tacho out.


texts: ESP8266 module cutting connection with PC via USB

texts: My Arduino UNO is connected directly to the ESP8266 (01) WiFi module. The Red and Blue LED flashes and it seems to work properly. But when I connect the UNO to my computer, the module refreshes at irregular intervals and the PC produces sounds as that of ejecting and inserting a USB. I don't know whether this is caused due to low voltage supplied from the USB or some other reason. Please help me out...


texts: Why do NRF24L01 modules only communicate in 1 direction

texts:
I have 2 NRF24L01 +pa +lna modules connected to 2 arduino mini pros. One of the modules is on a joystick and the other one is on a airplane. Everything worked perfectly until last week when they stopped communicating. So I wrote a simple receiver and transceiver code to see if they worked. The result is that if the module on the plane is the transceiver and the joystick is the receiver everything works fine. If they have the opposite roles then I only get empty messages onto the serial monitor way more often than the transceiver sends a message.
Receiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8);

const byte address[6] = "00001";

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

  radio.begin();
  radio.openReadingPipe(0, address);
  radio.startListening();

}

void loop() {
  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }

}

Transceiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7,8);

const byte address[6] = "00001";

void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.stopListening();

}

void loop() {

  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));
  delay (1000);
  // put your main code here, to run repeatedly:

}


texts: How can I poll bye array data for this scenario?

texts:
I want to send Arduino the following bytes as telegram from a master PC program through serial port:
0xAA 0x50 0xC1 0x01 0x01 0x01 0x00
and then I want Arduino to return(send back to PC) 20 bytes of telegram data such as:
0xAA 0x50 0xC1 0x01 0x01 0x01 0x00 0xAA 0x50 0xC1 0x01 0x01 0x01 0x00 0x00 0x00 0x00 0x00 0x00 0x00
How can this be done using Arduino Uno?


texts:
if(temperature < baselineTemp)else{
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(4, LOW);
}else if(temperature >= baselineTemp+2 && temperature < baselineTemp+4){
  digitalWrite(2, HIGH)
  digitalWrite(3, LOW)
  digitalWrite(4, LOW)
}else if(temperature >= baselineTemp+4 && temperature < baselineTemp+6){
  digitalWrite(2, HIGH)
  digitalWrite(3, HIGH)
  digitalWrite(4, LOW)
}else if(temperature >= baselineTemp+6){
  digitalWrite(2, HIGH)
  digitalWrite(3, HIGH)
  digitalWrite(4, HIGH)


texts: Why doesn't Serial.read() read multiple character?

texts:
I used multiple of Serial.read() and Serial.parseInt() to get characters and a number ( like "xy123" ) on an Arduino UNO.
Then I checked the result on Serial monitor.

Unfortunately I couldn't get the character with second Serial.read().

Here's the code:

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

void loop(){
  if (Serial.available() >0) {

    // I want to reacive the characters like "xy123"
    char input1 = Serial.read();
    char input2 = Serial.read();
    int value = Serial.parseInt();

    Serial.println(input1); // ok
    Serial.println(input2); // * no good * (-1)
    Serial.println(value);  // ok

    // Writing some codes with input1 ,input2 and value ...
  }
// I don't want to use delay().
}

How do I get the second character?

Thanks.


texts: Calculate the time since arduino started working for a year

texts: I want Calculate the time since arduino started working for a period of one year using arduino uno and when the period is over flip a light on


texts: ESP8266 Serial Communication with ATMega328P

texts:
I am isolating the ATMega328P from the Arduino Uno. I have used it for many other projects, so it does work as intended. Also, I have used my ESP8266-01 for other projects and works great (including serial communication).

I am trying to get the ESP8266-01 to make the ATMega328P pin 13 blink an LED. That is all.

When the ESP8266 is hooked to the TX/RX of the arduino board, the program works exactly as intended. I hook it up the exact same way to the ATMega328P and it doesn't work.

I am using baud rate of 9600 for the communication and using a 16MHz crystal for the ATMega328P.

simulate this circuit – Schematic created using CircuitLab

The controller is getting 3.3v from the supply as well. And pin 13 is supposed to turn on/off depending on the serial value. Below is the code for the ESP8266:

#include <ESP8266WiFi.h>

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

void loop() {
  delay(10000);
  Serial.write("LED ON");
  delay(10000);
  Serial.write("LED OFF");
}

And below is the code for the ATMega328P:

#include <SoftwareSerial.h>

SoftwareSerial esp8266(2,3);

void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600);
  pinMode(13, OUTPUT);
}

void loop()
{
  if(esp8266.available())
  {
    String command = "";
    while(esp8266.available())
    {
      command += (char)esp8266.read();
    }

    if(command == "LED ON") {
      digitalWrite(13, HIGH);
    }

    if(command == "LED OFF") {
      digitalWrite(13, LOW);
    }
  }

  delay(500);
}

As stated, they work great separately, but when I try serial communication with them together, it doesn't work.

P.S. I usually set my ESP8266 baud rate to 115200, but the ATMega328P, I believe, needs to run at 9600 because of the 16MHz clock frequency. Not sure about this part, though.

EDIT:

simulate this circuit


texts: How to fix this error (expected ',' or ';' before 'int' exit status 1)?

texts:
int Led1=13;
int Led2=10;
int tone1=6
  int D=300;

void setup(){
  pinMode(Led1,OUTPUT);
  pinMode(Led2,OUTPUT);
  pinMode(tone1,OUTPUT);
}

void loop(){
  int D;
digitalWrite(Led1,1);
digitalWrite(Led2,0);
delay(D);
}


texts:
How does one make an outgoing bluetooth connection?  I have already installed packages for bluetooth, and have run hcitool scan to find the BT address. And I'm using a USB BT dongle.

Output of lsusb

Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 058f:6254 Alcor Micro Corp. USB Hub
Bus 001 Device 003: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)
Bus 001 Device 004: ID 058f:6366 Alcor Micro Corp. Multi Flash Reader


texts:
I'm trying to compute Johnson resistance noise in a simple resistor circuit. However, since all frequencies contribute equally, I am getting an answer of infinity.

It then dawned upon me that the Arduino ADC probably detect frequencies larger than some cut off given by something called the full power bandwidth. Does anyone know this spec for the Due?