How do i convert the below Arduino Code to Embedded c code? - arduino

Can Anyone Please Convert the following Arduino Code to Embedded c code? I am very thankful to the one who converts this to an embedded c code. (this code is for Arduino lcd interfacing with Ultrasonic sensor)
#include <LiquidCrystal.h>
int inches = 0;
int cm = 0;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
pinMode(7, INPUT);
}
void loop() {
lcd.clear();
cm = 0.01723 * readUltrasonicDistance(7);
inches = (cm / 2.54);
if (cm<40){
lcd.setCursor(0, 0);
// print the number of seconds since reset:
lcd.print("Caution: ");
lcd.setCursor(0,1);
lcd.print("Objects Nearby");
delay(1000);
}
}
long readUltrasonicDistance(int pin)
{
pinMode(pin, OUTPUT); // Clear the trigger
digitalWrite(pin, LOW);
delayMicroseconds(2);
// Sets the pin on HIGH state for 10 micro seconds
digitalWrite(pin, HIGH);
delayMicroseconds(10);
digitalWrite(pin, LOW);
pinMode(pin, INPUT);
// Reads the pin, and returns the sound wave travel time in microseconds
return pulseIn(pin, HIGH);
}

I'm sorry but you can't because the dependencies of this code are LiquidCrystal.h (written in C++ and it contains dependencies like Arduino.h or Wire.h, libraries exclusive of Arduino software) and because methods like pinMode(int,int),digitalWrite(int,int),delayMicroseconds(int) comes from Arduino.h.
You can make your LiquidCrystal library rewriting it from the original.
Here some resources: C header and source, compile and upload, setup, standard avr libs.
I hope this can help. Good luck!

You can do that but is bit painful. Convert the class based function into c type functions. Remove dependant functions and replace the function by your own.
and use int main(void) instead of void loop().

Related

I am facing some issues while using arduino working with memory card and speaker, please help me

This is the code I wrote:
I set the pins given accordingly I checked my ultrasonic sensors, transistor, and resistors are in working condition. CS (in code denoted as chipset) is pinned in pin 10, resistor to 9, and that resistor is connected to the transistor, and then it is connected to the speaker.
#define trigPin1 3
#define echoPin1 2
#define trigPin2 4
#define echoPin2 5
#define trigPin3 7
#define echoPin3 8
#define cs 10
#include "SD.h"
#include "TMRpcm.h"
#include "SPI.h"
TMRpcm tmrpcm;
long duration, distance, RightSensor, BackSensor, FrontSensor, LeftSensor;
void setup()
{
tmrpcm.speakerPin = 9;
Serial.begin(9600);
if (!SD.begin(cs))
{
Serial.println("SD fail");
}
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(trigPin3, OUTPUT);
pinMode(echoPin3, INPUT);
}
void loop() {
SonarSensor(trigPin1, echoPin1);
RightSensor = distance;
tmrpcm.setVolume(6);
if (RightSensor > 10)
{
tmrpcm.play("RightFormatted.wav");
}
SonarSensor(trigPin2, echoPin2);
LeftSensor = distance;
if (LeftSensor > 10)
{
tmrpcm.play("LeftFormatted.wav");
}
SonarSensor(trigPin3, echoPin3);
FrontSensor = distance;
if (FrontSensor > 10)
{
tmrpcm.play("FrontFormatted.wav");
}
Serial.println(LeftSensor);
Serial.println(" - ");
Serial.print(FrontSensor);
Serial.print(" - ");
Serial.println(RightSensor);
}
void SonarSensor(int trigPin, int echoPin)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
}
The error I am getting is:
Error of this code
Instead of typing the name of the .wav file directly inside the .play method, create a const char variable to assign the name(s):
const char* audio1= "RightFormatted.wav";
then you can use it as:#
tmrpcm.play(audio1);
However, based on the examples from the library, you do not need the file extension, but I might be wrong in this regard.
Try first my proposal and please report your results

How do I program digital pins on arduino uno?

I'm trying to make a microcontroller with an arduino. I am supplying with +5volt from the arduino, sending it to an NC button (so i can manually decide when to output a certain timed pulse). After the button it goes to a pin that I have set as an inPin (pin8). Then I want the program to make pin 7 HIGH(with a delay), and then it goes to a transistor.
This is the code I tried making (I know almost nothing about coding):
int ledPin = 7;
int inPin = 8;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(inPin, INPUT);
}
void loop()
{
if (inPin=HIGH) {
digitalWrite(ledPin, HIGH);
}
delay (500);
digitalWrite(ledPin, LOW);
}
For some reason the outPin is HIGH all the time. I remembered to hook up a resistor to GND so the digital pin would stay LOW when supposed to be LOW.
Thanks in advance!
if(inPin=HIGH) is a mistake, first of all use "==" instead of "=". ALso you need to READ input pin state: int invalue = digitalRead(inPin);
Also, all pins by default coonfigured as inputs, so you don't need use pinMode(inPin, INPUT);
After those changes your code will look like:
int ledPin = 7;
int inPin = 8;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop()
{
if (digitalRead(inPin)==HIGH) digitalWrite(ledPin, HIGH);
delay (500);
digitalWrite(ledPin, LOW);
}

send sms with sim900 using arduino

#include <Password.h>
#include <Keypad.h>
#include <Servo.h>
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "sms.h"
Servo myservo;
Password password = Password( "1234" ); //password to unlock box, can be changed
SMSGSM sms;
int numdata;
boolean started=false;
char smsbuffer[160];
char n[20];
const byte ROWS = 4;
const byte COLS = 4;
// Define the Keymap
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = { 9, 8, 7, 6 };// Connect keypad COL0, COL1 and COL2 to these Arduino pins.
byte colPins[COLS] = { 5, 4, 3, 2 };
int x=0;
// Create the Keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup() //if i add sms(); function it workssss
{
Serial.begin(9600); //Start a Serial COM
Serial.println(F("ARDUINO SECURITY SYSTEM V1.0"));
Serial.print(F("Checking GSM COM..."));
if (gsm.begin(9600)) //Start the GSM COM
{
(sms.SendSMS("+XXXXX","Your Home Security system is powered up"));
Serial.println(F("Good To GO!!"));
}
else
{
Serial.println(F("Could not connect to GSM modem"));
}
Serial.write(254);
Serial.write(0x01);
delay(200);
pinMode(11, OUTPUT); //green light
pinMode(12, OUTPUT); //red light
myservo.attach(13); //servo on digital pin 9 //servo
keypad.addEventListener(keypadEvent);//add an event listener for this keypad
}
void loop(){
keypad.getKey();
myservo.write(0);
}
//take care of some special events
void keypadEvent(KeypadEvent eKey){
switch (keypad.getState()){
case PRESSED:
Serial.print("Enter : ");
Serial.println(eKey);
delay(10);
Serial.write(254);
switch (eKey){
case 'A': checkPassword(); delay(1); break;
case 'C': checkPassword(); delay(1); break;
case 'D': checkPassword(); delay(1); break;
case 'B': password.reset(); delay(1); break;
case '*': checkPassword(); break;
case '#': password.reset(); break;
default: password.append(eKey); delay(1);
}
}
}
void checkPassword(){
if (password.evaluate()){ //if password is right open box
Serial.println("Accepted");
Serial.write(254);delay(50);
//Add code to run if it works
myservo.write(5); //160deg
digitalWrite(11, HIGH);//turn on
delay(2000); //wait 5 seconds
digitalWrite(11, LOW);// turn off
}
else
{
Serial.println("Denied"); //if passwords wrong keep box locked
Serial.write(254);delay(10);
x++;
if(x==3)
//add code to run if it did not work
{
myservo.write(0);
digitalWrite(12, HIGH);
delay(500);
digitalWrite(12, LOW);
if (gsm.begin(9600))
{
(sms.SendSMS("+XXXXX","Your Home Security system is being bridged"));
Serial.println("USER WARNED");
}
}
}
}
;
}
In the picture the same code doesn't seem to work when I place the lines
if (gsm.begin(9600)) //Start the GSM COM
{
(sms.SendSMS("+8613668914901","Your Home Security system is being bridged"));
but this lines work great inside the void setup function.
How can I fix this problem? Inside the void setup the sketch works fine but when I also put the code in the function CheckPassword it doesn't send SMS.
I also tried to create a function let's say void SMS and call it in the checkPassword function but it doesn't solve the problem, btw the same function when called in the void setup works fine.
You are supposed to initialize the gsm only once, in the setup function.
In your code you attempt to initialize it again in the checkPassword method, and that is obviously not going to work.
Thus you should remove the line gsm.begin(9600) from the checkPassword function.
UPDATE 1:
In your scheme you reserve the pins 9, 8, 7, 6, 5, 4, 3, 2 for the Keyboard. However, at the same time you reserve pins 2, 3 for your GSM module (see GSM.cpp):
#define _GSM_TXPIN_ 2
#define _GSM_RXPIN_ 3
Using the same pins for multiple purposes can often result (if not done properly) in undefined behaviour which in the best scenario means that your sketch isn't doing what it is supposed to do, and in the worst scenario it might damage your components.
You are already using pins 0, 1 for the Serial library, but according to your code the pins 10, 11, 13 should still be free if you want to relocate the existing pins to your components.
Notice also the following warnings inside the GSM library:
[3] My shield doesn't work. Why?
Check this steps and then ask for support on the issues' page on google
code.
1) SIM900 and SIM908 require about 1 A during the hardest tasks.
You should have an external power source that can provide about
1 A at 8-12 V
2) If the SIM90X blinks (1 Hz) for some seconds and then turn off,
probably it's a communication's problem. Check the switch/jumpers
for Serial communication.
3) Arduino Uno has 2 KB of RAM. Library takes about 80% (we are working
to reduce it), if you use more than 20% left, Arduino can restart
or print on serial strange strings.
4) Check the jumper of communication, power source (battery or externel) and charge.

Arduino HC-SR04 NewPing Code Not Working

I was getting to know this ultrasonic detector with a simple code. All I was looking for was an output (my LED) to light up whenever the detector sensed an object within so many centimetres.
However the LED remains lit and the serial monitor just keeps spitting out the value '0.00cm'
I would appreciate any help, thanks.
(I do apologise if there is a very simple error I have overlooked)
#include <NewPing.h>
int TriggerPIN = 2;
int EchoPIN = 3;
int LEDPIN = 7;
void setup()
{
Serial.begin(9600);
//That started the distance monitor
pinMode(LEDPIN, OUTPUT);
pinMode(TriggerPIN, OUTPUT);
pinMode(EchoPIN, INPUT);
}
void loop()
{
float Distance, Duration;
digitalWrite(TriggerPIN, LOW);//These three blink the distance LED
delayMicroseconds(2);
digitalWrite(TriggerPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TriggerPIN, LOW);
Duration = pulseIn(EchoPIN, HIGH); //Listening and waiting for wave
Distance = (Duration*0.034/2);//Converting the reported number to CM
if (Distance > 50)
{
digitalWrite(LEDPIN,LOW);
}
else
{
digitalWrite(LEDPIN,HIGH);
}
Serial.print(Distance);Serial.print("cm");
Serial.println(" ");
delay(200);
}
A couple of things to try:
Change the serial print to display 'Duration', to see if the problem lies in the centimetre conversion.
If this is not the problem:
(Assuming you are using the NewPing 1.7 library, as found here. )
The NewPing library has a built in 'Ping' function, along with distance conversion.
Try replacing the start of your code with this:
#include <NewPing.h>
#define TRIGGER_PIN 2
#define ECHO_PIN 3
#define MAX_DISTANCE 200 // Maximum distance to ping for (cm). Up to ~450cm
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
You do not need to then set the Trigger and Echo pins as outputs in your setup.
In your main loop, use these methods to get time and distance in microsecs and centimetres:
unsigned int pingTime = sonar.ping(); //Gets the ping time in microseconds.
Serial.print(sonar.convert_cm(pingTime)); // Convert ping time in cm, serial out.
I hope this helps.

Arduino Ultra Sonic Sensor always returns 0

I am doing a basic project in Arduino UNO connecting an Ultra Sonic sensor (HC-SR04) which should print in the serial monitor the distance of the closest object but it always print 0.
This is my code:
long distance;
long time;
void setup(){
Serial.begin(9600);
pinMode(4, OUTPUT);
pinMode(2, INPUT);
}
void loop(){
digitalWrite(2,LOW);
delayMicroseconds(5);
digitalWrite(2, HIGH);
delayMicroseconds(10);
time = pulseIn(4, HIGH);
distance = int(0.017*time);
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm.");
delay(1000);
}
And this is the breadboard:
The primary issue that I see is that your code doesn't match your wiring diagram.
For example, your diagram shows Trig connected to pin 4. The Trig should be the output from your Arduino but you have it defined as an input.
The Echo is connected to pin 2 and it should be an input, but you have it defined as an output.
Finally, in your loop(), you are not even using pin 2 or pin 4, but pins 9 and 8. Another issue is the timing you use in setting the trigger pulse - it does not match the datasheet. I would do something like this (assuming that you are actually connected to the pins shown in your diagram):
#define sensorTrigPin 4
#define sensorEchoPin 2
void setup()
{
Serial.begin(9600);
pinMode(sensorTrigPin, OUTPUT);
pinMode(sensorEchoPin, INPUT);
}
void loop()
{
int pulseWidth = 0;
digitalWrite(sensorTrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(sensorTrigPin, LOW);
pulseWidth = pulseIn(sensorEchoPin, HIGH);
Serial.print("Pulse Width: ");
Serial.print(pulseWidth);
delay(1000);
}
Note that pulseWidth is just the amount of time that it takes from the beginning of the Echo pulse going high to the end of the same pulse (when it goes low). You would still have to calculate the distance based on the value of pulseWidth.
UPDATE BASED ON RECENT EDIT TO THE QUESTION
If you change a portion of your loop() code to this, it should work:
void loop(){
digitalWrite(4, HIGH); //was (2, LOW)
delayMicroseconds(10); //was (5)
digitalWrite(4, LOW); //was (2, HIGH)
//REMOVED EXTRA DELAY
time = pulseIn(2, HIGH); //was (4,HIGH);
... //Keep the rest of your code the same.
}
Try connecting your VCC of the sensor to 3V3 instead of 5V. This might sound odd, but I tried it and it worked well. Also, please make sure that your echo and trig pin match the code.

Resources