LCD I2C Interfacing With PIC16f877A - microcontroller

I am trying to interface an LCD using I2C but can't quite understand how to do it.
I found this example
Here's the code:
i2c.h:
/* File: I2C_LCD.h */
#define _XTAL_FREQ 16000000
#define I2C_BaudRate 100000
#define SCL_D TRISC3
#define SDA_D TRISC4
#define LCD_BACKLIGHT 0x08
#define LCD_NOBACKLIGHT 0x00
#define LCD_FIRST_ROW 0x80
#define LCD_SECOND_ROW 0xC0
#define LCD_THIRD_ROW 0x94
#define LCD_FOURTH_ROW 0xD4
#define LCD_CLEAR 0x01
#define LCD_RETURN_HOME 0x02
#define LCD_ENTRY_MODE_SET 0x04
#define LCD_CURSOR_OFF 0x0C
#define LCD_UNDERLINE_ON 0x0E
#define LCD_BLINK_CURSOR_ON 0x0F
#define LCD_MOVE_CURSOR_LEFT 0x10
#define LCD_MOVE_CURSOR_RIGHT 0x14
#define LCD_TURN_ON 0x0C
#define LCD_TURN_OFF 0x08
#define LCD_SHIFT_LEFT 0x18
#define LCD_SHIFT_RIGHT 0x1E
#define LCD_TYPE 2 // 0 -> 5x7 | 1 -> 5x10 | 2 -> 2 lines
//-----------[ Functions' Prototypes ]--------------
//---[ I2C Routines ]---
void I2C__Init();
void I2C__Wait();
void I2C__Start();
void I2C__RepeatedStart();
void I2C__Stop();
void I2C_ACK();
void I2C_NACK();
unsigned char I2C__Write(unsigned char data);
unsigned char I2C_Read_Byte(void);
//---[ LCD Routines ]---
void LCD_Init(unsigned char I2C_Add);
void IO_Expander_Write(unsigned char Data);
void LCD_Write_4Bit(unsigned char Nibble);
void LCD_CMD(unsigned char CMD);
void LCD_Set_Cursor(unsigned char ROW, unsigned char COL);
void LCD_Write_Char(char);
void LCD_Write_String(char*);
void Backlight();
void noBacklight();
void LCD_SR();
void LCD_SL();
void LCD_Clear();
I2c.c
#include <xc.h>
#include "I2C.h"
unsigned char RS, i2c_add, BackLight_State = LCD_BACKLIGHT;
//---------------[ I2C Routines ]-------------------
//--------------------------------------------------
void I2C__Init()
{
SSPCON = 0x28;
SSPCON2 = 0x00;
SSPSTAT = 0x00;
SSPADD = ((_XTAL_FREQ/4)/I2C_BaudRate) - 1;
SCL_D = 1;
SDA_D = 1;
}
void I2C__Wait()
{
while ((SSPSTAT & 0x04) || (SSPCON2 & 0x1F));
}
void I2C__Start()
{
I2C__Wait();
SEN = 1;
}
void I2C__RepeatedStart()
{
I2C__Wait();
RSEN = 1;
}
void I2C__Stop()
{
I2C__Wait();
PEN = 1;
}
void I2C_ACK(void)
{
ACKDT = 0; // 0 -> ACK
I2C__Wait();
ACKEN = 1; // Send ACK
}
void I2C_NACK(void)
{
ACKDT = 1; // 1 -> NACK
I2C__Wait();
ACKEN = 1; // Send NACK
}
unsigned char I2C__Write(unsigned char data)
{
I2C__Wait();
SSPBUF = data;
while(!SSPIF); // Wait Until Completion
SSPIF = 0;
return ACKSTAT;
}
unsigned char I2C_Read_Byte(void)
{
//---[ Receive & Return A Byte ]---
I2C__Wait();
RCEN = 1; // Enable & Start Reception
while(!SSPIF); // Wait Until Completion
SSPIF = 0; // Clear The Interrupt Flag Bit
I2C__Wait();
return SSPBUF; // Return The Received Byte
}
//======================================================
//---------------[ LCD Routines ]----------------
//------------------------------------------------------
void LCD_Init(unsigned char I2C_Add)
{
i2c_add = I2C_Add;
IO_Expander_Write(0x00);
__delay_ms(30);
LCD_CMD(0x03);
__delay_ms(5);
LCD_CMD(0x03);
__delay_ms(5);
LCD_CMD(0x03);
__delay_ms(5);
LCD_CMD(LCD_RETURN_HOME);
__delay_ms(5);
LCD_CMD(0x20 | (LCD_TYPE << 2));
__delay_ms(50);
LCD_CMD(LCD_TURN_ON);
__delay_ms(50);
LCD_CMD(LCD_CLEAR);
__delay_ms(50);
LCD_CMD(LCD_ENTRY_MODE_SET | LCD_RETURN_HOME);
__delay_ms(50);
}
void IO_Expander_Write(unsigned char Data)
{
I2C__Start();
I2C__Write(i2c_add);
I2C__Write(Data | BackLight_State);
I2C__Stop();
}
void LCD_Write_4Bit(unsigned char Nibble)
{
// Get The RS Value To LSB OF Data
Nibble |= RS;
IO_Expander_Write(Nibble | 0x04);
IO_Expander_Write(Nibble & 0xFB);
__delay_us(50);
}
void LCD_CMD(unsigned char CMD)
{
RS = 0; // Command Register Select
LCD_Write_4Bit(CMD & 0xF0);
LCD_Write_4Bit((CMD << 4) & 0xF0);
}
void LCD_Write_Char(char Data)
{
RS = 1; // Data Register Select
LCD_Write_4Bit(Data & 0xF0);
LCD_Write_4Bit((Data << 4) & 0xF0);
}
void LCD_Write_String(char* Str)
{
for(int i=0; Str[i]!='\0'; i++)
LCD_Write_Char(Str[i]);
}
void LCD_Set_Cursor(unsigned char ROW, unsigned char COL)
{
switch(ROW)
{
case 2:
LCD_CMD(0xC0 + COL-1);
break;
case 3:
LCD_CMD(0x94 + COL-1);
break;
case 4:
LCD_CMD(0xD4 + COL-1);
break;
// Case 1
default:
LCD_CMD(0x80 + COL-1);
}
}
void Backlight()
{
BackLight_State = LCD_BACKLIGHT;
IO_Expander_Write(0);
}
void noBacklight()
{
BackLight_State = LCD_NOBACKLIGHT;
IO_Expander_Write(0);
}
void LCD_SL()
{
LCD_CMD(0x18);
__delay_us(40);
}
void LCD_SR()
{
LCD_CMD(0x1C);
__delay_us(40);
}
void LCD_Clear()
{
LCD_CMD(0x01);
__delay_us(40);
}
main.c:
#include "I2C.h"
void main(void) {
I2C__Init();
LCD_Init(0x4E); // Initialize LCD module with I2C address = 0x4E
LCD_Set_Cursor(1, 1);
LCD_Write_String(" Welcome To ");
LCD_Set_Cursor(2, 1);
LCD_Write_String(" MicroDigiSoft ");
delay_ms(2500);
while(1)
{
}
return;
}
But I get these Errors:
Screenshot of Error
Screenshot of Error
I am using MikroC and one thing to note is that I have included the system libraries Lcd and Lcd Constants.
How can I fix these errors, and are there any examples of interfacing LCD I2C with microcontrollers apart from this?

You must import the I2C system libray in the the MikroC Library Manager, at the right panel. See the attached image:

Related

STM32F103xxxx In Application Programming Using Arduino

I am using Arduino_STM32 rogerclark's library.https://github.com/rogerclarkmelbourne/Arduino_STM32 .
Now I want to Develop an In Application Programming(IAP) like a bootloader. Take Code from SD card and Store in Controller flash at 0x8010000 and then jump to that location and run the loaded new application.
the code took from SD and stored into flash successfully done but after jump function called its printing null like this
13:29:04.933 [RX] - Starts............
13:29:07.970 [RX] - 20480 uploaded successfully.
NULNULNULNUL NULNUL
my Main IAP code is
Header file
#include <SPI.h>
#include <SD.h>
#include <EEPROM.h>
#include <stdint.h>
#include "libmaple/scb.h"
#include "usb_lib.h"
typedef void (*FuncPtr)(void);
#define SCS_BASE ((u32)0xE000E000)
#define NVIC_BASE (SCS_BASE + 0x0100)
#define SCB_BASE (SCS_BASE + 0x0D00)
#define SCS 0xE000E000
#define NVIC (SCS+0x100)
#define SCB (SCS+0xD00)
#define STK (SCS+0x10)
#define SCB_VTOR (SCB+0x08)
#define STK_CTRL (STK+0x00)
#define RCC ((u32)0x40021000)
#define RCC_CR RCC
#define RCC_CFGR (RCC + 0x04)
#define RCC_CIR (RCC + 0x08)
#define USB_LP_IRQ ((u8)0x14)
#define SET_REG(addr,val) do{ *(volatile uint32_t*)(addr)=val;} while(0)
#define GET_REG(addr) (*(vu32*)(addr))
#define pRCC ((rcc_reg_map *) RCC)
typedef struct {
u8 NVIC_IRQChannel;
u8 NVIC_IRQChannelPreemptionPriority;
u8 NVIC_IRQChannelSubPriority;
bool NVIC_IRQChannelCmd; /* TRUE for enable */
} NVIC_InitTypeDef;
#define RegBase (0x40005C00L)
#define CNTR ((volatile unsigned *)(RegBase + 0x40))
#define _SetCNTR(wRegValue) (*CNTR = (u16)wRegValue)
#define _GetCNTR() ((u16) *CNTR)
#define ISTR ((volatile unsigned *)(RegBase + 0x44))
#define _SetISTR(wRegValue) (*ISTR = (u16)wRegValue)
#define _GetISTR() ((u16) *ISTR)
void setupFLASH();
void usbDsbISR(void);
void nvicInit(NVIC_InitTypeDef *NVIC_InitStruct);
void nvicDisableInterrupts();
void setMspAndJump(u32 usrAddr);
void systemReset(void);
RESULT usbPowerOff(void);
void setupFLASH()
{
/* configure the HSI oscillator */
if ((pRCC->CR & 0x01) == 0x00)
{
u32 rwmVal = pRCC->CR;
rwmVal |= 0x01;
pRCC->CR = rwmVal;
}
/* wait for it to come on */
while ((pRCC->CR & 0x02) == 0x00) {}
}
void usbDsbISR(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USB_LP_IRQ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = FALSE;
nvicInit(&NVIC_InitStructure);
}
void nvicInit(NVIC_InitTypeDef *NVIC_InitStruct)
{
u32 tmppriority = 0x00;
u32 tmpreg = 0x00;
u32 tmpmask = 0x00;
u32 tmppre = 0;
u32 tmpsub = 0x0F;
scb_reg_map *rSCB = (scb_reg_map *) SCB_BASE;
nvic_reg_map *rNVIC = (nvic_reg_map *) NVIC_BASE;
/* Compute the Corresponding IRQ Priority --------------------------------*/
tmppriority = (0x700 - (rSCB->AIRCR & (u32)0x700)) >> 0x08;
tmppre = (0x4 - tmppriority);
tmpsub = tmpsub >> tmppriority;
tmppriority = (u32)NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority << tmppre;
tmppriority |= NVIC_InitStruct->NVIC_IRQChannelSubPriority & tmpsub;
tmppriority = tmppriority << 0x04;
tmppriority = ((u32)tmppriority) << ((NVIC_InitStruct->NVIC_IRQChannel & (u8)0x03) * 0x08);
tmpreg = rNVIC->IP[(NVIC_InitStruct->NVIC_IRQChannel >> 0x02)];
tmpmask = (u32)0xFF << ((NVIC_InitStruct->NVIC_IRQChannel & (u8)0x03) * 0x08);
tmpreg &= ~tmpmask;
tmppriority &= tmpmask;
tmpreg |= tmppriority;
rNVIC->IP[(NVIC_InitStruct->NVIC_IRQChannel >> 0x02)] = tmpreg;
/* Enable the Selected IRQ Channels --------------------------------------*/
rNVIC->ISER[(NVIC_InitStruct->NVIC_IRQChannel >> 0x05)] =
(u32)0x01 << (NVIC_InitStruct->NVIC_IRQChannel & (u8)0x1F);
}
void nvicDisableInterrupts()
{
nvic_reg_map *rNVIC = (nvic_reg_map *) NVIC_BASE;
rNVIC->ICER[0] = 0xFFFFFFFF;
rNVIC->ICER[1] = 0xFFFFFFFF;
rNVIC->ICPR[0] = 0xFFFFFFFF;
rNVIC->ICPR[1] = 0xFFFFFFFF;
SET_REG(STK_CTRL, 0x04); /* disable the systick, which operates separately from nvic */
}
void usbDsbBus(void)
{
// setPin(USB_DISC_BANK,USB_DISC_PIN);
usbPowerOff();
// SET_REG(USB_DISC_CR,
// (GET_REG(USB_DISC_CR) & USB_DISC_CR_MASK) | USB_DISC_CR_OUTPUT);
// resetPin(USB_DISC_BANK, USB_DISC_PIN); /* Pull DP+ down */
// volatile unsigned x = 500000; do { ; }while(--x);
// SET_REG(USB_DISC_CR,
// (GET_REG(USB_DISC_CR) & USB_DISC_CR_MASK) | USB_DISC_CR_INPUT); //Sets the PA12 as floating
input
}
RESULT usbPowerOff(void)
{
#define CNTR_PDWN (0x0002) /* Power DoWN */
#define CNTR_FRES (0x0001) /* Force USB RESet */
_SetCNTR(CNTR_FRES);
_SetISTR(0);
_SetCNTR(CNTR_FRES + CNTR_PDWN);
/* note that all weve done here is powerdown the
usb peripheral. we have no disabled the clocks,
pulled the USB_DISC_PIN pin back up, or reset the
application state machines */
return USB_SUCCESS;
}
void systemReset(void)
{
SET_REG(RCC_CR, GET_REG(RCC_CR) | 0x00000001);
SET_REG(RCC_CFGR, GET_REG(RCC_CFGR) & 0xF8FF0000);
SET_REG(RCC_CR, GET_REG(RCC_CR) & 0xFEF6FFFF);
SET_REG(RCC_CR, GET_REG(RCC_CR) & 0xFFFBFFFF);
SET_REG(RCC_CFGR, GET_REG(RCC_CFGR) & 0xFF80FFFF);
SET_REG(RCC_CIR, 0x00000000); /* disable all RCC interrupts */
}
void setMspAndJump(u32 usrAddr)
{
// Dedicated function with no call to any function (appart the last call)
// This way, there is no manipulation of the stack here, ensuring that GGC
// didn't insert any pop from the SP after having set the MSP.
typedef void (*funcPtr)(void);
u32 jumpAddr = *(vu32 *)(usrAddr + 0x04); /* reset ptr in vector table */
funcPtr usrMain = (funcPtr) jumpAddr;
SET_REG(SCB_VTOR, (vu32) (usrAddr));
asm volatile("msr msp, %0"::"g"(*(volatile u32 *)usrAddr));
usrMain(); /* go! */
}
main code is
#include "core_test.h"
#define CS PB9
File myFile;
char Name[15] = "ASCII.bin";
uint32_t Count = 0;
uint32_t total = 0;
#define FLASH_FLAG_EOP ((uint32_t)0x00000020) /* FLASH End of Operation flag */
#define FLASH_FLAG_PGERR ((uint32_t)0x00000004) /* FLASH Program error flag */
#define FLASH_FLAG_WRPRTERR ((uint32_t)0x00000010) /* FLASH Write protected error flag */
#define myFLASH_APP_ADDR 0x08000000
#define FLASH_APP_ADDR 0x08010000 //The first application start address (stored in FLASH)
#define STM_PAGE_SIZE 2048 //Note: The FLASH page size of STM32F103ZET6 is 2K.
//****************************************************************************************************
// Global variable declaration
char buff[STM_PAGE_SIZE];
int res;
unsigned int br;
void Jump2App(uint32_t Addr)
{
if (((*(uint32_t*)Addr) & 0x2FFE0000) == 0x20000000) //Check if the top address of the stack is legal.
{
// FLASH_Lock();
usbDsbISR(); //Serial1.println("1");
nvicDisableInterrupts(); //Serial1.println("2");
usbDsbBus(); //Serial1.println("3");
// Does nothing, as PC12 is not connected on teh Maple mini according to the schemmatic setPin(GPIOC, 12); // disconnect usb from host. todo, macroize pin
systemReset(); // resets clocks and periphs, not core regs
//Serial1.println("4");
setMspAndJump(Addr);
}
}
void FirmwareUpdate(void)
{
int PageOffest = 0;
int ByteOffest;
if (! IsFileExists(Name)) return;
myFile = SD.open(Name);
while (1)
{
if (Read_data_from_File(buff))
{
FLASH_Unlock();
// FLASH_ClearFlag(((uint16_t)0x00000034));
// FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
FLASH_ErasePage(FLASH_APP_ADDR + PageOffest);
for (ByteOffest = 0; ByteOffest < STM_PAGE_SIZE; ByteOffest += 2)
{
total = total + 2;
FLASH_ProgramHalfWord(FLASH_APP_ADDR + PageOffest + ByteOffest, *(uint16_t*)(buff + ByteOffest));
}
FLASH_Lock();
PageOffest += STM_PAGE_SIZE;
// Serial1.println(PageOffest);
}
else if (myFile.size() <= total) break;
}
myFile.close();
Serial1.println(total);
//myFile.close();
}
void setup()
{
afio_cfg_debug_ports(AFIO_DEBUG_SW_ONLY);
Serial1.begin(9600);
if (!SD.begin(CS))
{
Serial1.println("No SD............");
Jump2App(FLASH_APP_ADDR);
}
delay(1000);
Serial1.println("Starts............"); delay(2000);
FirmwareUpdate();
Jump2App(FLASH_APP_ADDR);
while (1);
}
void loop()
{}
bool IsFileExists(char FileName[])
{
if (SD.exists(FileName)) return 1;
else return 0;
}
bool Read_data_from_File(char str[])
{
memset(str, 255, 2048);
uint16_t i = 0;
if (myFile.size() < total)
{
//memset(str, 255, 2048);
// Serial1.println("File Closed");
// Serial1.println(total);
return 0;
}
if (myFile)
{
while (i < 2048)
{
str[i++] = myFile.read();
Count = Count + 1;
if (myFile.size() < Count)
{
//memset(str, 255, 2048);
// Serial1.println("File Closed");
// Serial1.println(Count);
return 1;
}
}
}
else return 0;
}
my user Application code is ASCIItable example code which is given in arduino
before generation this ASCII.bin file
i have changed ROM location address 0x8000000 to 0x8010000 and compiled the file.
Is this process correct,
please help me where I am doing wrong

How do I send multiple 32 byte strings to I2C master?

I have multiple variable length strings which do not exceed 32 bytes each which need to be sent via I2C between 2 Arduino Nanos. I use # to terminate each string. I can successfully send and receive the first string, but for the life of me I can't figure out how to send the succeeding strings. The samples I am testing with look like this:
String answer = "12345,123.4,50.6,12345#";
String answerV = "4.10,4.15,4.13,4.05,4.18,0#";
Master Code
#include <Wire.h>
int esc = 0;
int throttle = 80;
void setup() {
Wire.begin();
Serial.begin(115200);
Serial.println("I2C Master ready!");
esc = throttle * 100 / 180;
}
void loop() {
delay(500);
Serial.println("Receive data");
Wire.requestFrom(9,32);
String response = "";
Serial.println(Wire.available());
while (Wire.available())
{
char b = Wire.read();
response += b;
}
String dataString = response;
int hashIndex = dataString.indexOf('#');
String SportData = dataString.substring(0, hashIndex);
Serial.println(SportData);
String SDdata = String (esc) + "," + String(SportData);
Serial.println(SDdata);
}
Slave Code
#include <Wire.h>
byte ANSWERSIZE= 22;
String answer = "12345,123.4,50.6,12345#";
String answerV = "4.10,4.15,4.13,4.05,4.18,0#";
void setup() {
Wire.begin(9);
Wire.onRequest(requestEvent); // data request from Master
Serial.begin(115200);
Serial.println("I2C Slave ready!");
ANSWERSIZE = answer.length();
}
void requestEvent() {
byte response[ANSWERSIZE];
for (byte i=0;i<ANSWERSIZE;i++)
{
response[i] = (byte)answer.charAt(i);
}
Wire.write(response,sizeof(response));
}
void loop() {
delay(50);
}
Can someone please show me how this can be done?
A simple idea is to keep track of the number of times requestEvent() is called, and use that to decide what to send back to the master.
Here is the code (n.b. I took the liberty to optimise it a bit):
Master:
#include <Wire.h>
/**
* globals
*/
int esc = 0;
int throttle = 80;
char i2c_buffer[33];
/**
* setup & loop
*/
void setup()
{
Serial.begin(115200);
Wire.begin();
esc = throttle * 100 / 180;
i2c_buffer[32] = '\0';
Serial.println("I2C Master ready!");
}
void loop()
{
delay(500);
Wire.requestFrom(9, 32);
for (byte i = 0; i < 32 && Wire.available(); ++i)
{
i2c_buffer[i] = Wire.read();
if (i2c_buffer[i] == '#') {
i2c_buffer[i] = '\0';
break;
}
}
Serial.print(esc);
Serial.print(',');
Serial.println(i2c_buffer);
}
Slave:
#include <Wire.h>
/**
* globals
*/
const byte DATA_SIZE = 2;
String data[DATA_SIZE] = {
"12345,123.4,50.6,12345#",
"4.10,4.15,4.13,4.05,4.18,0#"
};
/**
* setup & loop
*/
void setup()
{
Serial.begin(115200);
Wire.begin(9);
Wire.onRequest(requestEvent); // data request from Master
Serial.println("I2C Slave ready!");
}
void loop()
{
delay(50);
}
/**
* help functions
*/
void requestEvent()
{
static byte req_number = 0;
Wire.write(reinterpret_cast<const unsigned char*>(data[req_number].c_str()),
data[req_number].length());
req_number = (req_number + 1) % DATA_SIZE;
}
Note: I don't have two Arduino devices, so I could not test this code. If you spot some bugs, report back and I'll fix them.

integrating the AdafruitFona GSM shield with tiny gps library

i need help in integrating the two libraries so that i can send the GPS data via GSM . Information regarding the use of two special Serial is needed and also a help with the code is needed .
The below segmnet containts the code for the GPS shield this has to be used to generate the location and this data has to be sent via gsm to a mobile number.
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
It requires the use of SoftwareSerial, and assumes that you have a
4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 4, TXPin = 3;//was 4 and 3;
static const uint32_t GPSBaud = 9600;
// The TinyGPS++ object
TinyGPSPlus gps;
// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);
void setup()
{
Serial.begin(115200);
ss.begin(GPSBaud);
Serial.println(F("GPS GSM tracking system"));
Serial.println(F("Sabdadon Presents"));
Serial.print(F("Search and Rescue")); Serial.println(TinyGPSPlus::libraryVersion());
Serial.println(F("Sabarish"));
Serial.println();
}
void loop()
{
// This sketch displays information every time a new sentence is correctly encoded.
while (ss.available() > 0)
if (gps.encode(ss.read()))
displayInfo();
if (millis() > 500000 && gps.charsProcessed() < 10)
{
Serial.println(F("No GPS detected: check wiring."));
while(true);
}
}
void displayInfo()
{
delay(10000);
Serial.print(F("Location: "));
if (gps.location.isValid())
{
Serial.print(gps.location.lat(), 5);
Serial.print(F(","));
Serial.print(gps.location.lng(), 5);
// latitude=gps.location.lat();
//longitude=gps.location.lng();
//if(latitude && longitude)
}
else
{
Serial.print(F("INVALID"));
}
Serial.print(F(" Date/Time: "));
if (gps.date.isValid())
{
Serial.print(gps.date.month());
Serial.print(F("/"));
Serial.print(gps.date.day());
Serial.print(F("/"));
Serial.print(gps.date.year());
}
else
{
Serial.print(F("INVALID"));
}
Serial.print(F(" "));
if (gps.time.isValid())
{
if (gps.time.hour() < 10) Serial.print(F("0"));
Serial.print(gps.time.hour());
Serial.print(F(":"));
if (gps.time.minute() < 10) Serial.print(F("0"));
Serial.print(gps.time.minute());
Serial.print(F(":"));
if (gps.time.second() < 10) Serial.print(F("0"));
Serial.print(gps.time.second());
Serial.print(F("."));
if (gps.time.centisecond() < 10) Serial.print(F("0"));
Serial.print(gps.time.centisecond());
}
else
{
ss.read();
Serial.print(F("INVALID"));
}
Serial.println();
}
FOR GSM
#include "Adafruit_FONA.h"
#define FONA_RX 2//2
#define FONA_TX 3//3
#define FONA_RST 4//4
char replybuffer[255];
#include <SoftwareSerial.h>
#include <AltSoftSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);
uint8_t type;
void setup()
{
while (!Serial);
Serial.begin(115200);
Serial.println(F("FONA basic test"));
Serial.println(F("Initializing....(May take 3 seconds)"));
fonaSerial->begin(4800);
if (! fona.begin(*fonaSerial)) {
Serial.println(F("Couldn't find FONA"));
while (1);
}
type = fona.type();
Serial.println(F("FONA is OK"));
Serial.print(F("Found "));
switch (type) {
case FONA800L:
Serial.println(F("FONA 800L")); break;
case FONA800H:
Serial.println(F("FONA 800H")); break;
case FONA808_V1:
Serial.println(F("FONA 808 (v1)")); break;
case FONA808_V2:
Serial.println(F("FONA 808 (v2)")); break;
case FONA3G_A:
Serial.println(F("FONA 3G (American)")); break;
case FONA3G_E:
Serial.println(F("FONA 3G (European)")); break;
default:
Serial.println(F("???")); break;
}
// Print module IMEI number.
char imei[15] = {0}; // MUST use a 16 character buffer for IMEI!
uint8_t imeiLen = fona.getIMEI(imei);
if (imeiLen > 0) {
Serial.print("Module IMEI: "); Serial.println(imei);
}
}
void loop()
{ Serial.print(F("FONA> "));
while (! Serial.available() ) {
if (fona.available()) {
Serial.write(fona.read());
}
}
// send an SMS!
char sendto[21], message[141];
flushSerial();
Serial.print(F("Send to #"));
readline(sendto, 20);
Serial.println(sendto);
Serial.print(F("Type out one-line message (140 char): "));
readline(message, 140);
Serial.println(message);
if (!fona.sendSMS(sendto, message)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("Sent!"));
}
}
void flushSerial() {
while (Serial.available())
Serial.read();
}
char readBlocking() {
while (!Serial.available());
return Serial.read();
}
uint16_t readnumber() {
uint16_t x = 0;
char c;
while (! isdigit(c = readBlocking())) {
//Serial.print(c);
}
Serial.print(c);
x = c - '0';
while (isdigit(c = readBlocking())) {
Serial.print(c);
x *= 10;
x += c - '0';
}
return x;
}
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) {
uint16_t buffidx = 0;
boolean timeoutvalid = true;
if (timeout == 0) timeoutvalid = false;
while (true) {
if (buffidx > maxbuff) {
//Serial.println(F("SPACE"));
break;
}
while (Serial.available()) {
char c = Serial.read();
//Serial.print(c, HEX); Serial.print("#"); Serial.println(c);
if (c == '\r') continue;
if (c == 0xA) {
if (buffidx == 0) // the first 0x0A is ignored
continue;
timeout = 0; // the second 0x0A is the end of the line
timeoutvalid = true;
break;
}
buff[buffidx] = c;
buffidx++;
}
if (timeoutvalid && timeout == 0) {
//Serial.println(F("TIMEOUT"));
break;
}
delay(1);
}
buff[buffidx] = 0; // null term
return buffidx;
}
Here is a step-by-step to mix your GPS input device and your GSM output device.
Remainder for Arduino principles:
The void setup() function is performed one time after startup.
The void loop() function is performed periodically after the
setup().
Step1 - declaration of GPS device and Serial link
// GPS and Serial link
static const int RXPin = 4, TXPin = 3;//was 4 and 3;
static const uint32_t GPSBaud = 9600;
// The TinyGPS++ object
TinyGPSPlus DeviceGPS;
// The serial connection to the GPS device
SoftwareSerial SerialGPS(RXPin, TXPin);
Step2 - declaration of GSM/FONA device and Serial link
Including the SendTo SMS number !!!
#define FONA_RX 2//2
#define FONA_TX 3//3
#define FONA_RST 4//4
// The serial connection to the GSM device
SoftwareSerial SerialFONA = SoftwareSerial(FONA_TX, FONA_RX);
// The FONA/GSM Cellular Module device
Adafruit_FONA DeviceFONA = Adafruit_FONA(FONA_RST);
// The destination SMS number
static const char *sSendTo = "<NUMBER>";
Step3 - setup() function for (Console, GPS and GSM)
It is possible to add some extra Init.
// only execute once
void setup()
{
// Wait and Init Console
while (!Serial); // Serial over USB
Serial.begin(115200);
// Init GPS link
SerialGPS.begin(GPSBaud);
Serial.print(F("TinyGPSPlus ver: "));
Serial.println(TinyGPSPlus::libraryVersion());
// Init GSM link
SerialFONA.begin(4800);
if (! DeviceFONA.begin(SerialFONA)) {
Serial.println(F("Couldn't find FONA"));
while (1); // Stop working
}
// Add some extra Init
}
Step4 - loop() function to wait GPS location and send SMS
It is possible to use String() to create the SMS based on the
acquired DeviceGPS.location.lng() and DeviceGPS.location.lat().
// executed periodicaly
void loop()
{
// check until GPS message
while (SerialGPS.available() > 0) {
// get for a complete GPS message
DeviceGPS.encode(SerialGPS.read());
}
// flush GSM serial link
while (SerialFONA.available() > 0) {
if (DeviceFONA.available()) {
DeviceFONA.flush();
}
}
// send an SMS!
char sendto[21], message[141];
// Wait for location (lng, lat, alt) is OK
if (DeviceGPS.location.isValid()) {
// ==> create SMS with longitude & latitude
}
}

serial output anomaly in atmega2560

I am facing a problem with atmega2560 serial outport port. When I connect AVRISPmkII programmer to atmega2560, all serial port gives output data at specified baud rate but when I disconnect programmer, there is no output but 1 second led blinks. I don't think that this is the code proble!m. I have not tried it with other programmer as that is all I have. The code is very simple anyway - blink led at 1 second and give output through RS232 port.
Voltage at reset pin is 5V and at sck is about 1.19V whether or not programmer is connected.
What is the problem here ?
The figure shows ISP and serial port circuits.
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include <string.h>
void USART0_init(void) /*************** USART 0 ***********************/
{
UCSR0A = 0x00;
UCSR0B = 0b00011000;
UCSR0C = 0b00000110;
UBRR0H = 0x00;
UBRR0L = 103; //baud rate: 9600, right - rx, tx, gnd - left
}
void USART0_putc(char data)
{
while(!(UCSR0A&0x20));
UDR0=data;
}
void USART0_puts(char* str){
while(*str) {USART0_putc(*str++);}
}
void USART1_init(void) /*************** USART 1 ***********************/
{
UCSR1A = 0x00;
UCSR1B = 0b10011000;
UCSR1C = 0b00000110;
UBRR1H = 0x00;
UBRR1L = 103; //baudrate: 9600
}
void USART1_putc(char data)
{
while(!(UCSR1A&0x20));
UDR1=data;
}
void USART1_puts(char* str){
while(*str) {USART1_putc(*str++);}
}
char t = 0;
char rx_buf1[50];
ISR(USART1_RX_vect)
{
cli();
t = UDR1;
rx_buf1[cnt1++] = t;
if (t == 0x0a){ // detect EOL \n FOR NOW
rx_buf1[cnt1] = '\0';
sprintf(out_buf1, "\r\nS1, ");
strcat(out_buf1, (const char*)rx_buf1);
sprintf(out_buf1, ", /");
USART0_puts(out_buf1);
cnt1 = 0;
rx_complete1 = 1;
}
if (cnt1 >= 50){
cnt1 = 0;
}
sei();
}
void timer_init(void)
{
cli();
TCCR1B = (1<<WGM12); //CTC mode
OCR1A = 1561; //100 ms
TIMSK1 |= (1<<OCIE1A);
TCCR1B |= (1<<CS12)|(0<<CS11)|(1<<CS10);
}
void dev_init(void)
{
DDRA = 0x0F;
PORTA = 0x00;
timer_init();
stdout = &uart0_str;
stderr = &uart1_str;
USART0_init();
USART1_init();
sei();
}
int main(void)
{
dev_init();
while(1)
{
process();
}
return 0;
}
volatile unsigned char tick_100ms;
char out_buf[100];
float speed = 4.3;
void process(void){
static unsigned char lc=1;
static uint8_t tick_cnt = 0;
if (tick_100ms){
tick_100ms = 0;
tick_cnt++;
if (tick_cnt == 10){
tick_cnt = 0;
PORTA = ~lc; /* this code is for blinking 4 LEDS */
lc = lc*2; /* very 1 seconds alternately*/
if (lc >8) lc = 1;
sprintf(out_buf, "S1, speed: %05.2f/\r\n", (double)speed);
USART0_puts(out_buf);
USART1_puts(out_buf);
}
}
}
I gave posted my code below.
The uart 1 interrupt code is not needed because there is no incoming data. Disabling them made no difference.

Uint8_to Char array Arduino sketch

I am using this sh1 function. Instead of printing the hash value I want to store it in a char array or string for further processing.
#include "sha1.h"
#include <stdlib.h>
void setup(){
Serial.begin(9600);
}
void loop() {
uint8_t *hash;
Sha1.init();
Sha1.print("This is a message to hash");
hash = Sha1.result();
for (int j=0;j<20;j++)
Serial.print("0123456789abcdef"[hash>>4]);
Serial.print("0123456789abcdef"[hash&0xf]);
}
Serial.println();
delay(1000);
}
char digitArray[]= {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
char buffer[40];
for (int i = 0; i<40; i+=2){
buffer[i] = digitArray[(hash[i/2] & 0xF0) >> 4];
buffer[i+1] = digitArray[(hash[i/2] & 0x0F)];
}

Resources